← DP Patterns · guided lesson

DP Patterns

1 / 20 · story

the story

State-machine DP

Every tool here exists because something was too slow or broke without it. Here is what.

1952–67 · Richard Bellman (stages and states); Andrew Viterbi (best path per state per time step)

Bellman's dynamic programming (see the Dynamic Programming chapter) already thinks in stages and states: at each stage you are in some state, and the best future depends only on that state. In 1967 Andrew Viterbi published a decoding algorithm for convolutional codes that keeps, for every state of the encoder at every time step, the best path that ends there — one best number per state per step, the same table the stock problems fill. The stock-trading series itself (I–IV, cooldown, fee) is interview folklore with no inventor.

the problem it solved

Choosing the best sequence of actions when what you may do next depends on the mode you are in — holding or not, cooling down, trades used — without listing every sequence.

why it matters: without it

Every "what I may do next depends on what I did before" question would mean trying every action sequence — exponential in the number of days.

sources: Bellman — On the Theory of Dynamic Programming (PNAS, 1952) ↗ · Viterbi — Error bounds for convolutional codes and an asymptotically optimum decoding algorithm (IEEE Trans. Information Theory, 1967) ↗ · Forney — The Viterbi Algorithm: A Personal History (arXiv, 2005) ↗

also in this chapter: Regular-expression matching · Palindromic substrings: centres, tables and Manacher · Knapsack in disguise: signs to a subset sum · Weighted interval scheduling (sort + DP + binary search) · Game DP (minimax on what's left)