Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming/State Machine DP (Stocks)

Learn the pattern · ~15 min

State Machine DP (Stocks)

also called finite-state DP, stock DP

When the future depends only on which of a few modes you're in (holding, just sold, resting, trades left), keep the best value for each mode at each step and move between modes with a few rules.

Signalsbuy/sell with rulesalternate/forbidden adjacent choicesa few modes per positionLearn first1D / Fibonacci-style
Cheat sheet and practice

Reach for it when you read

  • +Buying and selling a stock with a rule: a cooldown, a fee, at most k trades.
  • +At each step you're in one of a few modes, and rules say which mode can follow which.
  • +The last choice limits the next one: the digit you're on, whether you swapped, whether the last pick was even or odd.
  • +The brute force tries every history (3ⁿ), but the past only matters through a flag or two.

Not this one when

  • ×The future depends on which items were used, not a few modes: bitmask DP.
  • ×The state is a number that can be large (weight left, money left): knapsack DP.
  • ×A cheapest route through a graph where each node also has a mode: Dijkstra over (node, mode).

Learn State Machine DP (Stocks)

First, what is a "state machine"?

A state here is just a mode you can be in. With shares, at the end of any day you're in one of two modes: you hold a share, or you have cash and no share.

A machine is the set of arrows between modes: from cash you can buy (go to hold), from hold you can sell (go to cash), and either way you can do nothing and stay put.

State machine DP walks the days one by one and keeps one best number per mode: the most money you can have if you end today in that mode. A few numbers per day, instead of every history.

Two modes, day by day

Take the prices [2, 5, 1, 3, 6, 4]. You may buy and sell as often as you like, but hold at most one share. The rule for each day:

Each mode's new value = the best of its arrows in: stay where you were, or come from the other mode.

So hold = max(hold, cash − price) (keep it, or buy today) and cash = max(cash, hold + price) (stay out, or sell today). Before day 0 you have cash 0, and holding is impossible.

day price what happens hold cash
0 2 buy for 2 from cash 0; nothing to sell −2 0
1 5 keep the −2 (buying at 5 is worse); sell: −2 + 5 = 3 −2 3
2 1 buy from cash 3: 3 − 1 = 2 beats −2; selling at 1 is worse 2 3
3 3 keep 2; sell: 2 + 3 = 5 2 5
4 6 keep 2; sell: 2 + 6 = 8 2 8
5 4 buy from cash 8: 8 − 4 = 4; selling: 2 + 4 = 6 is worse 4 8

The answer is the cash at the end: 8. That's buy 2, sell 5, buy 1, sell 6. Notice each row only looked at the row above it.

The code for it

C++
long long hold = LLONG_MIN / 2, cash = 0;   // you can't own a share before day 0
for (int p : prices) {
    long long h = hold;                     // yesterday's hold
    hold = max(hold, cash - p);             // keep it, or buy today
    cash = max(cash, h + p);                // stay out, or sell today
}
// answer: cash

You don't need to memorise this. It's the table above: two numbers, two arrows into each.

Why copy hold into h first? Because cash must use yesterday's hold. If you overwrite hold and then read it, you'd buy and sell on the same day as if it were two days. Here that happens to cost nothing, but with more rules it breaks the answer, as you'll see.

Fine, but how does this help us?

Here's a classic problem: Best Time to Buy and Sell Stock with Cooldown. Same rules, but after you sell, you must skip one day before you can buy again.

On [2, 5, 1, 3, 6, 4] the 8 is gone: it sold at 5 on day 1 and bought at 1 on day 2, the very next day. Try the plans by hand:

Text
plan                                   money
buy 2, sell 5, skip 1, buy 3, sell 6   3 + 3 = 6
buy 1, sell 6                          5
buy 2, sell 6                          4
buy 2, sell 5 (and nothing else)       3

The answer is 6.

The brute force

The choices: each day, wait, or buy (if you're free), or sell (if you hold). The recursion carries the day and the mode, and returns the most money you can still make from that day on.

C++
long long go(int i, bool holding, bool cooling) {   // most money still to make from day i
    if (i == n) return 0;
    long long best = go(i + 1, holding, false);                  // wait
    if (holding)
        best = max(best, prices[i] + go(i + 1, false, true));    // sell, tomorrow is blocked
    else if (!cooling)
        best = max(best, -prices[i] + go(i + 1, true, false));   // buy
    return best;
}
// answer: go(0, false, false)

Draw a corner of the calls:

  • go(0, free)
    • wait → go(1, free)
      • wait → go(2, free)
        • wait → go(3, free)← here
      • buy 5 → …
    • buy 2 → go(1, hold)
      • sell 5 → go(2, cooling)
        • forced wait → go(3, free)← and here again
      • wait → …

With up to two choices a day this explodes: 84 calls for 6 days, about 6 × 10⁷ for 30 (2 s by day 36), and it grows by about 1.75× per day. For n = 5000 that's about 5 × 10¹²²¹ calls. Time limit exceeded.

The one thought: only the mode matters

Point at the two go(3, free) calls. One got there by waiting three days, with 0 money. The other bought at 2, sold at 5 and sat out the cooldown, with 3 money.

What can each of them still do? Exactly the same things: they stand on day 3, price 3, with no share and free to buy. Their futures are identical, so the best future is the same number. The past only matters through the day and the mode, not through which trades got you there.

That's 3 modes × n days, about 3n different questions, while the tree asks them over and over.

Memoise it

C++
long long goMemo(int i, bool holding, bool cooling) {
    if (i == n) return 0;
    if (done[i][holding][cooling]) return memo[i][holding][cooling];   // asked before
    long long best = goMemo(i + 1, holding, false);
    if (holding) best = max(best, prices[i] + goMemo(i + 1, false, true));
    else if (!cooling) best = max(best, -prices[i] + goMemo(i + 1, true, false));
    done[i][holding][cooling] = true;
    return memo[i][holding][cooling] = best;
}

The bottom-up table

Each day reads only the day before, so three variables are enough. Split "no share" in two: sold (sold today, so tomorrow is blocked) and rest (free to buy). The arrows: rest → hold (buy), hold → sold (sell), sold → rest (the cooldown). Hold and rest may also stay.

C++
const long long NEG = LLONG_MIN / 2;      // "impossible"
long long hold = NEG, sold = NEG, rest = 0;
for (int p : prices) {
    long long h = hold, s = sold, r = rest;   // yesterday, frozen
    hold = max(h, r - p);                     // keep it, or buy from rest only
    sold = h + p;                             // sell today
    rest = max(r, s);                         // stay free, or finish the cooldown
}
// answer: max(sold, rest)

Dry run

Same prices. −∞ means "impossible": you can't have sold before day 0.

day price what happens hold sold rest
0 2 buy from rest 0 −2 −∞ 0
1 5 sell: −2 + 5 −2 3 0
2 1 buy from rest 0: −1 beats −2; rest takes the 3 from sold −1 −1 3
3 3 buy from rest 3: 3 − 3 = 0, the second buy 0 2 3
4 6 sell: 0 + 6 0 6 3
5 4 rest takes the 6 0 4 6

The answer is the best mode you may end in, max(sold, rest) = 6, the same answer as the brute force.

Now the trap from earlier: drop the h, s, r copies, and sold feeds rest on the same day. The cooldown vanishes and these prices give 8, not 6.

Why it's O(n)

Count what happens per day: three numbers, three lines. That's O(n) time, and O(1) space since only yesterday is kept.

From about 1.75ⁿ calls down to 3n steps, by remembering one best value per mode instead of every history.

Only one trade? Buy from zero

Best Time to Buy and Sell Stock: one buy, one sell. Buying must start from 0 money, not from earlier profits:

C++
hold = max(hold, 0LL - p);                // the only buy, from 0

On our prices: 5 (buy 1, sell 6).

A fee? Put it on the sell arrow

With Transaction Fee: each sale pays a fee. Only one arrow changes:

C++
cash = max(cash, h + p - fee);

With fee 2: 4 (buy 2, sell 5, buy 1, sell 6, minus two fees).

At most k trades? One pair of modes per trade

Stock III and IV: buy[j] and sell[j] mean "during the j-th trade". The j-th buy comes from the (j − 1)-th sell:

C++
buy[j] = max(buy[j], sell[j - 1] - p);
sell[j] = max(sell[j], buy[j] + p);

With k = 2: 8. Here sell[j] may read today's buy[j]: buying and selling on one day earns 0, so it's harmless.

Remember this

  • Draw the modes and arrows first; each arrow is one term in a max.
  • Impossible modes start at −∞, not 0.
  • Trap: copy yesterday before writing today.
  • The answer is the best mode you're allowed to end in.
  • Whenever a problem walks step by step and the past only matters through a flag or two (holding, cooling, the last digit), it's this pattern.

Practise it on Best Time to Buy and Sell Stock, then Stock II (two modes), with Transaction Fee, with Cooldown (three modes), Stock III (count the trades) and Knight Dialer (no stocks: the digit is the mode).

Watch it work, line by line

Best Time to Buy and Sell Stock with Cooldown ↗, prices = [1, 2, 3, 0, 2] → 3 (buy, sell, cooldown, buy, sell). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

At each step, does the future depend only on which of a few modes I'm in (holding, cooling down, trades used, last choice), not on the whole history?

Reach for it when

  • +buy/sell with rules
  • +alternate/forbidden adjacent choices
  • +a few modes per position
  • +n up to 1e5 with O(1) states

It fails when

  • ×Unlimited free transactions, no constraintsuse Greedy: sum every positive delta
  • ×Only one previous value matters, no modesuse Plain 1-D DP
  • ×The state space is not small or explodes combinatoriallyuse Re-model, or bitmask / knapsack DP
  • ×k >= n/2 transactions: effectively unlimiteduse Greedy O(n) sum, skip the huge array

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Why does hold start at −∞ instead of 0?Reveal

    Before any buy you can't hold a share. 0 would mean a free share you could sell for pure profit.

  • 2Why snapshot yesterday's values before updating?Reveal

    Each update must read yesterday. Using today's values lets you buy and sell on the same day, or skip the cooldown.

  • 3With a cooldown, which mode can you buy from?Reveal

    Only rest. Sold flows into rest the next day, never straight into hold.

Practice ladder

every problem →
  1. 1Best Time to Buy and Sell Stockone tradeEasy
  2. 2Best Time to Buy and Sell Stock IItwo modesMedium
  3. 3Best Time to Buy and Sell Stock with Transaction FeefeeMedium
  4. 4Best Time to Buy and Sell Stock with Cooldownthe hookMedium
  5. 5Best Time to Buy and Sell Stock IIIat most 2 tradesHard
  6. 6Knight Dialerno stocksMedium
  7. 7Best Time to Buy and Sell Stock IVat most k tradesHard
  8. 8Minimum Swaps To Make Sequences Increasingno stocksHard

Finished State Machine DP (Stocks)? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to State Machine DP (Stocks)

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial