InterviewHubPRO
Section Overview
Q99

Question 99 of 100

Part 11: Dynamic Programming & Knapsack (91 - 100)

99%
DSA Patterns (Multi-Lang)•Part 11: Dynamic Programming & Knapsack (91 - 100)

Best Time to Buy and Sell Stock with Cooldown.

In Simple Words: State machine DP with three states:

  • holding: either keep holding or buy after resting (rest - price).
  • sold: sell stock held today (holding + price).
  • rest: either rest again or rest after selling yesterday (max(rest, sold)).
  • Time: $O(N)$ | Space: $O(1)$
Multi-Language Solutions
Switch tabs or choose All
def maxProfit(prices: list[int]) -> int:
    sold, rest, hold = 0, 0, float('-inf')
    for p in prices:
        prev_sold = sold
        sold = hold + p
        hold = max(hold, rest - p)
        rest = max(rest, prev_sold)
    return max(sold, rest)