-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathbest-time-to-buy-and-sell-stock-with-cooldown.py
53 lines (43 loc) · 1.63 KB
/
best-time-to-buy-and-sell-stock-with-cooldown.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from functools import lru_cache
from enum import Enum
class Solution:
def maxProfitRecursive(self, prices: List[int]) -> int:
class Phase(Enum):
BUY = 0
SELL = 1
COOLDOWN = 2
@lru_cache(None)
def backtrack(pos: int, prev_phase: Phase) -> int:
if pos == len(prices):
return 0
result = 0
if prev_phase == Phase.COOLDOWN:
result = max(result, backtrack(pos + 1, Phase.BUY) - prices[pos])
result = max(result, backtrack(pos + 1, Phase.COOLDOWN))
elif prev_phase == Phase.BUY:
result = max(result, backtrack(pos + 1, Phase.SELL) + prices[pos])
result = max(result, backtrack(pos + 1, Phase.BUY))
elif prev_phase == Phase.SELL:
result = max(result, backtrack(pos + 1, Phase.COOLDOWN))
return result
return backtrack(0, Phase.COOLDOWN)
def maxProfit(self, prices: List[int]) -> int:
buy = [0] * (len(prices) + 1)
sell = [0] * (len(prices) + 1)
cooldown = [0] * (len(prices) + 1)
buy[0] = float("-inf")
sell[0] = float("-inf")
for pos in range(1, len(prices) + 1):
cooldown[pos] = max(
sell[pos - 1],
cooldown[pos - 1],
)
buy[pos] = max(
cooldown[pos - 1] - prices[pos - 1],
buy[pos - 1],
)
sell[pos] = max(
sell[pos - 1],
buy[pos - 1] + prices[pos - 1],
)
return max(buy[-1], sell[-1], cooldown[-1])