122. Best Time to Buy and Sell Stock II
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
这道题没什么好说的,只要前一天比今天价格少,就买前一天,卖今天。
class Solution:
def maxProfit(self, prices: List[int]) -> int:
res = 0
for i in range(len(prices)-1):
res+= max(0,prices[i+1]-prices[i])
return res
上面是greedy,那如果我们用buy (hold) & sell 来做呢
class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy = -prices[0]
sell = 0
for price in prices[1:]:
prevBuy = buy
buy = max(buy,sell - price)
sell = max(sell,prevBuy + price)
return sell
Last updated
Was this helpful?