Best Time to Buy and Sell Stock with Cooldown
Difficulty: Medium
Given a stock's price on each of n days, find the maximum total profit. You can buy and sell as many times as you like, but:
- You can hold only one share at a time (sell before buying again).
- After selling, you must wait a full day before buying again — a cooldown.
Examples
Input: prices = [1,2,3,0,2]
Output: 3
Buy at 1, sell at 2 (profit 1), cooldown, buy at 0, sell at 2 (profit 2). Total: 3.
Input: prices = [1]
Output: 0
There's no second day to sell on, so the best move is to do nothing.
Constraints
1 <= prices.length <= 5000
0 <= prices[i] <= 1000
Approach
Instead of one "best profit so far", track three per day: the best profit if you're holding a share, if you just sold today, and if you're resting (free to buy, not in cooldown).
Each day's values depend only on the previous day's: - holding: the same as yesterday (do nothing), or buy today using yesterday's resting profit. - just sold: yesterday's holding profit plus today's price. - resting: the better of resting yesterday or just sold yesterday (the cooldown has passed).
The answer is the better of "just sold" and "resting" on the last day — you never want to end holding a share.
Solutions
Brute Force — Recursion
Each day, recursively try both choices for the current state (holding or not): do nothing, or buy/sell. Selling jumps two days ahead for the cooldown. Correct, but re-explores the same (day, state) pairs again and again.
function maxProfit(prices) {
const n = prices.length;
function solve(day, holding) {
if (day >= n) return 0;
let best = solve(day + 1, holding); // do nothing today
if (holding) {
best = Math.max(best, prices[day] + solve(day + 2, false)); // sell, then cooldown tomorrow
} else {
best = Math.max(best, -prices[day] + solve(day + 1, true)); // buy
}
return best;
}
return solve(0, false);
}Time: O(2^n) · Space: O(n) — recursion depth
Optimal — Bottom-Up 2D Table
Build a table with one row per day and three columns — holding, just sold, resting. Each row is computed only from the previous one.
function maxProfit(prices) {
const n = prices.length;
if (n === 0) return 0;
const HOLD = 0, SOLD = 1, REST = 2;
const table = Array.from({ length: n }, () => new Array(3).fill(0));
table[0][HOLD] = -prices[0];
table[0][SOLD] = -Infinity; // can't have sold yet on day 0
table[0][REST] = 0;
for (let day = 1; day < n; day++) {
table[day][HOLD] = Math.max(table[day - 1][HOLD], table[day - 1][REST] - prices[day]);
table[day][SOLD] = table[day - 1][HOLD] + prices[day];
table[day][REST] = Math.max(table[day - 1][REST], table[day - 1][SOLD]);
}
return Math.max(table[n - 1][SOLD], table[n - 1][REST]);
}Time: O(n) · Space: O(n) — can be reduced to O(1) by keeping only the previous day's three values