Dynamic Programming · Pattern 6 of 12

State machine DP: every Buy and Sell Stock problem

Each day you are in a state: holding a share or not (plus how many trades are left, or a cooldown). Write how each state is reached from yesterday's states, and keep one variable per state.

5 variations · 6 problems · 6 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Buy and sell on given days to maximise profit
  • Rules about what you may do next: a fee, a cooldown, a limit of k trades
  • Your options today depend on what you did before, not just on the day

The template

State Machine DP - Stock Problems
// Unlimited trades with a fee (fee = 0 is Stock II). States: cash (no share) and hold (one share).
int maxProfitFee(int[] prices, int fee) {
    int cash = 0, hold = Integer.MIN_VALUE / 2;     // you cannot hold a share before day 0
    for (int p : prices) {
        int newCash = Math.max(cash, hold + p - fee);   // rest, or sell today
        hold = Math.max(hold, cash - p);                 // rest, or buy today
        cash = newCash;
    }
    return cash;
}

// Cooldown: after selling you must rest a day, so a buy uses the cash from two days ago
int maxProfitCooldown(int[] prices) {
    int cash = 0, prevCash = 0, hold = Integer.MIN_VALUE / 2;
    for (int p : prices) {
        int newCash = Math.max(cash, hold + p);
        hold = Math.max(hold, prevCash - p);
        prevCash = cash;
        cash = newCash;
    }
    return cash;
}

// At most k transactions (k = 1 is Stock I, k = 2 is Stock III)
int maxProfitK(int k, int[] prices) {
    int[] buy = new int[k + 1], sell = new int[k + 1];   // best after the j-th buy / j-th sell
    Arrays.fill(buy, Integer.MIN_VALUE / 2);
    for (int p : prices)
        for (int j = 1; j <= k; j++) {
            buy[j] = Math.max(buy[j], sell[j - 1] - p);
            sell[j] = Math.max(sell[j], buy[j] + p);
        }
    return sell[k];
}

The variations

  1. 1One transaction

    Walk the prices and keep the lowest price so far. Selling today earns price - lowest. It is the k = 1 case of the state machine.

  2. 2Unlimited transactions, with or without a fee

    Two states: cash and hold. cash = max(cash, hold + p - fee), hold = max(hold, cash - p). With no fee this equals adding every rising step.

  3. 3Cooldown after selling

    A sale blocks tomorrow's buy. Buying today must use the cash from two days ago, so keep one more variable: yesterday's cash.

  4. 4At most k transactions

    One buy[j] and sell[j] state per transaction number. buy[j] builds on sell[j - 1], so the count of trades is part of the state. Stock III is k = 2.

  5. 5More practice

    More problems that use this pattern. Try them once the variations above feel easy.

Mistakes to avoid

  • Updating hold with the cash value you just changed today, which lets you sell and rebuy in a way the rules forbid (it matters for the cooldown).
  • Starting hold at 0: you do not own a share before buying one, so it must start at minus infinity.
  • Charging the fee on both the buy and the sell: it is charged once per transaction.
Next: Knapsack: choose items under a capacity →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.