MEDIUM NC#113 Dynamic Programming
309. Best Time to Buy and Sell Stock with Cooldown
๐ Problem
You are given an array prices where prices[i] is the price of a given stock on the ith day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions: - After you sell your stock, you cannot buy stock on the next day (i.e., cooldown 1 day). - You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขArray DP table updates
- โขState transition thinking
- โขBase case initialization
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Dynamic Programming reasoning pattern
๐ก Approach
- โ Use DP to track max profit at each state
- โ Three states: hold (bought), sold (just sold), cooldown
- โ hold[i] = max(hold[i-1], cooldown[i-1] - prices[i])
- โ sold[i] = max(sold[i-1], hold[i-1] + prices[i])
- โ cooldown[i] = max(cooldown[i-1], sold[i-1])
- โ Time: O(n), Space: O(1)
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse DP to track max profit at each state
- โขThree states: hold (bought), sold (just sold), cooldown
- โขhold[i] = max(hold[i-1], cooldown[i-1] - prices[i])
Common Pitfalls
- โขsold[i] = max(sold[i-1], hold[i-1] + prices[i])
- โขcooldown[i] = max(cooldown[i-1], sold[i-1])
- โขTime: O(n), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
maxProfitWithCooldown([1,2,3,0,2]); Expected:
2 Test Case 2
Not run Input:
maxProfitWithCooldown([1]); Expected:
0 Test Case 3
Not run Input:
maxProfitWithCooldown([]); Expected:
0 ๐ Code Editor
๐ค Output