Given daily stock prices, return the maximum profit from as many buy/sell transactions as you like, holding at most one share, where after selling you must wait one day (cooldown) before buying again.
Track the best profit ending each day in three states: hold (own a share), sold (just sold, cooling down tomorrow) and rest (free to buy). Each day's states come from yesterday's.
1function maxProfit(prices: number[]): number {2let hold = -Infinity, sold = 0, rest = 0;3for (const p of prices) {4const prevSold = sold;5sold = hold + p; // sell today6hold = Math.max(hold, rest - p); // keep holding, or buy from rest7// rest: cooldown ends (or keep resting)8rest = Math.max(rest, prevSold);9}10return Math.max(sold, rest);11}
| hold |
|---|
| sold |
| rest |
Before day 0: can't hold, nothing sold.
Space: play/pause · ←/→: step