309. Best Time to Buy and Sell Stock with Cooldown
Solution
-
There’re 3 states,
hold
,nohold
, ‘cooldown’. -
Keep the max profit up to time
i
when we are in these three states. -
hold
can be achieved bydonothing (hold)
orbuy (nohold - p)
-
nohold
can be achieved bydonothing (nohold)
orsell (cooldown, because after we sell sth, we directly enter the cooldown state)
-
cooldown
can be achieved bysell (hold + p)
-
The initial state is
nohold
.
dic = {}
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
hold, nohold, cooldown = -float('inf'), 0, -float('inf')
for p in prices:
hold, nohold, cooldown = max(hold, nohold - p), max(nohold, cooldown), hold + p
return max(nohold, cooldown)
NEXTTarget Sum