Best Time to Buy and Sell Stock with Cooldown
LeetCode 309 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
dfs(i, can_buy): selling moves to i+2 — that skipped day is the cooldown.
ನಾನು Best Time to Buy and Sell Stock with Cooldown (LeetCode 309) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — State Machine / Stocks ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Each day you are in one of two modes: free to buy, or holding a share. In buy mode you either buy or wait; in hold mode you either sell or wait. Selling forces you to skip the next day, which is just a jump of two days in the recursion.
Approach
- 1
State: (index, can_buy) → best profit from this day onward.
- 2
If can_buy: max(−price + dfs(i+1, holding), dfs(i+1, can_buy)).
- 3
If holding: max(+price + dfs(i+2, can_buy), dfs(i+1, holding)).
- 4
Base case: past the last day the profit is 0.
- 5
lru_cache makes the 2n states each solve once.
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
State machine + memoPythonO(n) time · O(n) space
from functools import lru_cache
class Solution:
def maxProfit(self, prices: List[int]) -> int:
#two choices
#buy, sell
#buy/cool down
#sell/cool down
#if sell we need to wait for a day
n = len(prices)
@lru_cache(maxsize=None)
def dfs(index,can_buy):
if index>=n:
return 0
if can_buy:
buy = -prices[index]+dfs(index+1,False)
cooldown= dfs(index+1,True)
return max(buy,cooldown)
else:
sell = prices[index]+dfs(index+2,True)
cooldown= dfs(index+1,False)
return max(sell,cooldown)
return dfs(0,True)
Best Time to Buy and Sell Stock with Cooldown — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Best Time to Buy and Sell Stock with Cooldown ಹಿಂದಿನ intuition ಏನು?
Each day you are in one of two modes: free to buy, or holding a share. In buy mode you either buy or wait; in hold mode you either sell or wait. Selling forces you to skip the next day, which is just a jump of two days in the recursion.
Best Time to Buy and Sell Stock with Cooldown (LeetCode 309) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. State: (index, can_buy) → best profit from this day onward. 2. If can_buy: max(−price + dfs(i+1, holding), dfs(i+1, can_buy)). 3. If holding: max(+price + dfs(i+2, can_buy), dfs(i+1, holding)). 4. Base case: past the last day the profit is 0. 5. lru_cache makes the 2n states each solve once.
Best Time to Buy and Sell Stock with Cooldown ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(n). Space: O(n). (Accepted approach: State machine + memo.)
Best Time to Buy and Sell Stock with Cooldown ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
The cooldown applies after a sell, not after a buy. Index can jump past n by two — the base case must use ≥ n.