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.