Best Time to Buy and Sell Stock with Cooldown

MediumDP · State Machine🧩 State Machine DPLeetCode #309 ↗Updated

Problem

prices[i] is a stock's price on day i. You may trade as many times as you like, holding at most one share at a time, but the day right after a sale is a mandatory cooldown on which you cannot buy. Return the maximum total profit.
Inputprices=[1,4,2,3,0,5]Output8 (buy 1, sell 4, cool, buy 0, sell 5)
Inputprices=[3,1,4,2,6]Output5
Inputprices=[7]Output0

1 ≤ prices.length ≤ 5000  ·  0 ≤ prices[i] ≤ 1000

Try it yourself

Java
class Solution {
    public int maxProfit(int[] prices) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Each day you are in one of three states — holding, just sold (tomorrow is cooldown), or resting (free to buy). Each state's best profit depends only on yesterday's three values.
PatternState Machine DP

Instinct Each step you are in one of a few modes (holding, sold, cooling down) with rules for switching - keep one DP value per mode and update all of them every step.

Memory hack Name the moods, draw the moves, max the arrows - every arrow in your state diagram becomes exactly one line of code.

Open the State Machine DP guide →

Approaches

Brute ForceRecursion over Every Choice

Time O(2n)Space O(n)

At day i you either do nothing, or act: buy if empty-handed, sell if holding. Selling jumps to day i+2, which encodes the cooldown. Exploring every branch finds the best profit.

Java
public int maxProfit(int[] prices) {
    return best(prices, 0, false);
}

private int best(int[] prices, int i, boolean holding) {
    if (i >= prices.length) return 0;
    int skip = best(prices, i + 1, holding);
    int act = holding
        ? prices[i] + best(prices, i + 2, false)  // sell, then forced cooldown
        : -prices[i] + best(prices, i + 1, true); // buy
    return Math.max(skip, act);
}

Captures the rules exactly, but the same (day, holding) pair is re-solved exponentially often.

At a glance

LevelApproachTimeSpace
Brute ForceRecursion over Every ChoiceO(2n)O(n)
BetterMemoised DP on (day, holding)O(n)O(n)
OptimalThree-State Machine, O(1) SpaceO(n)O(1)
Common pitfalls
  • Buying from sold instead of rest — that skips the cooldown.
  • Updating rest with today's new sold instead of yesterday's (save prevSold).
  • Starting hold at 0 — it would pretend you own a free share.
Interview tips
  • Name the states aloud and draw the transitions before writing any code.
  • Show the recursion first, point out the repeated (day, holding) pairs, then memoise.
  • Finish by rolling the table into variables and mention the 714 (fee) variant.
Pattern
State-machine DP → a day-by-day process with a few modes and rules on which mode can follow which.
My notes saved in this browser