Best Time to Buy and Sell Stock with Cooldown

Best Time to Buy and Sell Stock with Cooldown

O(n) version - 40ms

1
2
3
4
5
6
7
8
9
10
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
notHold, notHold_cooldown, hold = 0, float('-inf'), float('-inf')
for p in prices:
hold, notHold, notHold_cooldown = max(hold, notHold - p), max(notHold, notHold_cooldown), hold + p
return max(notHold, notHold_cooldown)

test code

1
2
In [103]: s = Solution(); t = s.maxProfit([1,2,3,0,2]); print(t)
3

leet code