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 SolutionsPython 3 • JavaScript • TypeScript • Java • C++
Switch tabs or choose Alldef 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)