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

๐Ÿ“š Reference Solution

โ–ผ

๐Ÿ”— Related Problems

โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit