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)

O(n · k)

Track dp for each state (holding / sold / rest) and transition day by day.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn first1D / Fibonacci-styleUnlocksAliens Trick (Lagrangian relaxation / WQS binary search)
0%
mastery
0/10 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

Buy/sell with rules (cooldown, fee, at most k transactions), or a few modes per position that change what you can do next.

  1. 1Brute force

    Recursion over every action at every day.

  2. 2The observation

    Exponential action sequences: only the current mode matters for the future.

  3. 3Why it works

    dp[i][s] is the best value after i steps ending in mode s; each day you only transition between a few modes.

Reach for it when

  • +Each step has a few discrete states with transition rules — buy/sell/hold, on/off, rest.
  • +Stock trading with cooldown, fee, or a transaction cap.
  • +Any 'mode you're in changes what you can do next' sequence problem.

Not 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

Intuition

Some DP problems are clearest as a little state machine: on each day you're in one of a few states, and each day you take a transition. Stock problems are the poster child — you're always either holding a share or not holding one, and each day you can stay put, buy (not→hold), or sell (hold→not).

Read the full intuition

Track the best money you can have in each state:

  • hold = most cash if you currently own a share (you've paid for it).
  • free = most cash if you own nothing.

Each day, both update from yesterday's values:

Text
new_hold = max(hold, free - price)     # keep holding, or buy today
new_free = max(free, hold + price)     # stay out, or sell today

Start hold = -infinity (can't hold before buying), free = 0. The answer is free at the end (you never want to finish holding).

Variants just add states or tweak transitions:

  • Cooldown: after selling you must rest a day → add a cooldown state, and buy only from cooldown two-back / a rested free.
  • Transaction fee: subtract the fee on sell (hold + price - fee).
  • At most k transactions: make hold/free arrays indexed by transactions-used; loop k each day.

Key idea

The reflex: when the problem has a few modes with rules for switching between them, name the states, write each day's transition, and roll the variables. It's just 1-D DP with more than one running value.

Why it costs what it costs

Time O(n) or O(n·k). one pass for fixed states; O(n·k) when indexing states by transaction count.

Space O(1) or O(k). a constant number of rolling state variables, or arrays of size k.

Practice

Next · Foundation

Best Time to Buy and Sell Stock

Track min price so far (2-state machine).

0/10 solved
  • Best Time to Buy and Sell StockFoundationFoundationAmazon, MetaEasy
  • Best Time to Buy and Sell Stock IIApply it · Unlimited transactions.Apply itAmazon, CitadelMedium
  • Best Time to Buy and Sell Stock with Transaction FeeOne change · Fee per transaction.One changeMedium
  • Best Time to Buy and Sell Stock with CooldownOne change · Cooldown after selling.One changeMedium
  • Best Time to Buy and Sell Stock IIITwists · At most 2 transactions.TwistsHard
  • Best Time to Buy and Sell Stock IVBranches · At most k transactions.BranchesHard
  • Minimum Swaps To Make Sequences IncreasingAdvanced · Different domain, same state idea.AdvancedHard
  • Maximum Alternating Subsequence SumMastery checkMastery checkMedium
  • Knight DialerMedium
  • Minimum Difficulty of a Job ScheduleHard

Pitfalls

Classic bugs

  • !Init hold = 0 pretends you hold a share for free: start it at -infinity.
  • !Same-day update order: using today's hold for free means sell right after buy. Fine if unlimited; else use temps.
  • !Cooldown: buy must come from the rested free state two days back, not yesterday's free.
  • !Fee: subtract it once per transaction (conventionally on sell), not on both buy and sell.
Go deepervariants and techniques · 2 combinations · resources

Variants and techniques

  • Divide & Conquer DP OptimisationFor dp[i][j] = min_k dp[i-1][k] + C(k, j) with opt(i, j) non-decreasing in j, compute each row by recursing on the middle j with a narrowed k range.
  • Convex Hull Trick / Li Chao TreeWhen dp[i] = min_j (m_j * x_i + b_j), keep lines on a lower envelope (monotone deque or Li Chao tree) and query min at x_i in O(1)/O(log n).
  • Unlimited transactionsTwo rolling states hold/free. Best Time to Buy and Sell Stock II.
  • Single transactionTrack min price so far; best = max(best, price − min). Best Time to Buy and Sell Stock.
  • CooldownAdd a rest state; buy only after a cooldown day. With Cooldown.
  • Transaction feeSubtract fee on each sell transition. With Transaction Fee.
  • At most kState arrays indexed by transactions used; loop k each day. Stock III (k=2), Stock IV.

Combinations

  • Convex Hull Trick / Li Chao Tree+1D / Fibonacci-style

    cost is product of a term of j and a term of i

    Convex Hull Trick / Li Chao Tree:
    queries the lower envelope of lines
    1D / Fibonacci-style:
    defines dp[i] = min_j (m_j * x_i + b_j) + c_i

    Monster Game IMonster Game IIThe Fair Nut and Rectangles

  • Divide & Conquer DP Optimisation+Prefix Sum

    split array into k parts minimising sum of squared/segment costs

    Divide & Conquer DP Optimisation:
    monotone split points per layer
    Prefix Sum:
    O(1) segment cost

    Subarray Squares

Resources

  • DP lecture notesErrichto · video
  • AtCoder Educational DP ContestAtCoder · sheet
  • Introduction to DPUSACO Guide · course
  • Dynamic Programming PatternsLeetCode discuss · article
  • Dynamic Programming playlistAditya Verma · video
  • Bitmask DPUSACO Guide · course
  • Digit DPCodeforces · blog
Interval DPBitmask DP
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial