-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feature: best time to buy and sell stock with cooldown top down revisit
- Loading branch information
1 parent
7a02a2b
commit 5c852df
Showing
2 changed files
with
14 additions
and
10 deletions.
There are no files selected for viewing
18 changes: 11 additions & 7 deletions
18
dynamic_programming/BestTimeToBuyAndSellStockWithCooldown.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,15 +1,19 @@ | ||
from functools import cache | ||
from functools import lru_cache | ||
from typing import List | ||
|
||
|
||
# O(n) time || O(n) space | ||
def max_profit(self, prices: List[int]) -> int: | ||
@cache | ||
def dp(i, buy): | ||
def max_profit_top_down(self, prices: List[int]) -> int: | ||
@lru_cache(None) | ||
def dp(i, holding): | ||
if i >= len(prices): | ||
return 0 | ||
|
||
cooldown = dp(i + 1, buy) | ||
return max(dp(i + 1, not buy) - prices[i], cooldown) if buy else max(dp(i + 2, not buy) + prices[i], cooldown) | ||
if holding: | ||
res = max(prices[i] + dp(i + 2, False), dp(i + 1, True)) | ||
else: | ||
res = max(-prices[i] + dp(i + 1, 1), dp(i + 1, 0)) | ||
|
||
return dp(0, True) | ||
return res | ||
|
||
return dp(0, False) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters