重点在于buy和sell各是一个状态,考虑当天买和之前买哪个收益更高,当天卖和之前卖哪个收益更高
class Solution:
def maxProfit(self, prices: List[int]) -> int:
#考虑当天买和之前买哪个收益更高,当天卖和之前卖哪个收益更高
n = len(prices)
buy = -prices[0]
sell = 0
for p in prices:
buy = max(buy, -p)
sell = max(sell, p + buy)
return sell
class Solution:
def maxProfit(self, prices: List[int]) -> int:
buy = -prices[0]
sell = 0
for p in prices:
buy = max(buy, sell - p)
sell = max(sell, p + buy)
return sell
class Solution:
def maxProfit(self, prices: List[int]) -> int:
fbuy = -prices[0]
fsell = 0
sbuy = -prices[0]
ssell = 0
for p in prices:
fbuy = max(fbuy, -p)
fsell = max(fsell, p + fbuy)
sbuy = max(sbuy, fsell - p)
ssell = max(ssell, p + sbuy)
return ssell