Dynamic Programming

A 20-inch steel rod can be cut 524,288 ways. Plain recursion makes 1,048,576 calls to find the best cut. Write each answer down the first time, and 211 calls do the same job.

Pick a method, then drag the rod length. Watch the best cut and the work bars. Then we build, piece by piece, memos, tables, the four-step recipe and five classic problems.

You need recursion (a function that calls itself) and Big-O in outline. We build the rest from zero.

Follows Chapter 15 of Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein (CLRS), third edition. The rod prices and the matrix chains are the book's. The devices and the other toy inputs are our own.

Cut the rod three ways

20

Prices for 1 to 10 inches are the CLRS table: $1, 5, 8, 9, 10, 17, 17, 20, 24, 30. A piece longer than 10 inches has no price, so it earns $0. The call counts are exact for the recursion that tries every first piece from 1 to n.

Chapter 0

The Same Question, Asked Again and Again

Cut a steel rod for the most money, and count how often plain recursion repeats itself

You sell steel rods. A customer buys pieces, and the price depends on the length. A whole 4-inch rod sells for $9. Cut it into two 2-inch pieces and you get $5 + $5 = $10. Where should you cut a rod of n inches?

Length (inches)12345678910
Price ($)1589101717202430

A rod of n inches has n − 1 places to cut, and each place is cut or not. So there are 2n−1 ways to cut it: 8 for a 4-inch rod, 524,288 for a 20-inch rod.

Plain recursion does a little better. Try every length i for the first piece. Sell it for its price, then solve the rest, n − i inches, the same way. Keep the best total. How many calls does that make? Call the number of calls for a rod of length n T(n).

Say it aloud

T of n equals one, plus the sum over j from zero to n minus one of T of j, which equals two to the n.

T(n)
T of n the number of calls plain recursion makes for a rod of n inches.
1
one the call for length n itself.
Σj=0n−1
the sum over j from zero to n minus one add one term for each leftover length j, from 0 to n − 1.
T(j)
T of j the calls made to solve the leftover of j inches. T(0) = 1.
2n
two to the n the closed form: the count doubles each time the rod grows one inch.
In plain words

The call for length n counts 1. Then it calls once for every shorter leftover j, and each of those calls makes T(j) calls of its own. Add them all to get T(n).

With numbers

T(0) = 1, T(1) = 2, T(2) = 4, T(3) = 8. So T(4) = 1 + 1 + 2 + 4 + 8 = 16. A 4-inch rod costs 16 calls, but only 5 different questions exist: lengths 0 to 4.

Grow the call tree

Each dot is one call, labelled with the leftover length. Teal dots ask a question for the first time. Yellow dots ask it again. Drag the length and count the yellow.

4

The tree is exact: a call for length k calls lengths k − 1 down to 0, in that order.

Two facts make this problem a fit for dynamic programming: solve each smaller problem once, keep the answer, and build bigger answers from kept ones. The first fact is overlapping subproblems: the same smaller question comes back many times. The second is optimal substructure: the best answer contains best answers to smaller questions. Chapter 3 proves the second.

Symptom: the rod program answers at n = 20 in a second, then hangs at n = 40.

Measure: count the calls. The count doubles with every inch: 240 is about 1.1 trillion.

Fix: remember each answer the first time you compute it. That is Chapter 1.

The road

  1. Memoization: write each answer down. The hero's Memo button.
  2. Bottom-up tables: fill from the smallest case up. The hero's Table button.
  3. The recipe: two ingredients, four steps, and a problem where they fail.
  4. Matrix-chain order: where to put the brackets.
  5. Longest common subsequence: the thread two strings share.
  6. Edit distance: three moves and a free match.
  7. Knapsack and coin change: the showcase, take or skip.
  8. Trees and DAGs: DP without a grid.
  9. The field guide: recurrences, numbers, code and links.
Plain recursion cuts a 5-inch rod by trying every first piece. How many calls does it make?

Chapter 1

Memoization: Write the Answer Down

Keep the recursion, add a notebook, and watch 16 calls drop to 11

First, write the rule that plain recursion follows. Call the best money you can get from a rod of n inches r(n). Call the price of a piece of i inches pi. An empty rod earns nothing, so r(0) = 0.

Say it aloud

r of n equals the max over i from one to n of p-i plus r of n minus i.

r(n)
r of n the most money a rod of n inches can earn, in dollars.
max1 ≤ i ≤ n
the max over i from one to n try every first-piece length i and keep the largest total.
pi
p-i the price of the first piece, i inches long, from the price table.
r(n − i)
r of n minus i the most the leftover n − i inches can earn, cut the best way.
In plain words

For each first piece i, add its price p-i to the best money for the leftover, r of n minus i. The largest of those totals is r of n.

With numbers

With r(0..3) = 0, 1, 5, 8: r(4) = max(1 + 8, 5 + 5, 8 + 1, 9 + 0) = max(9, 10, 9, 9) = 10. Two 2-inch pieces win.

Memoization keeps this recursion and adds a notebook, the memo. Before a call computes r(k), it looks in the memo. If the answer is there, it returns it at once: a cache hit. If not, it computes r(k), writes it down, and returns it.

Step the memoized calls

The left shows the call stack. The right shows the memo. Press Step. Blue is the call working now; teal is a stored answer or a hit.

4

The memo holds r(0) = 0 before the first call, as in the code below.

For n = 4 the memo makes 11 calls, not 16. The memo computes each length from 1 to 4 once; the other 7 calls are hits. In general the calls are 1 + n(n + 1)/2, so the work grows as n2. At n = 20 that is 211 calls, against 1,048,576.

pythondef memo_rod(p, n):                 # p[i] = price of i inches, p[0] = 0
    memo = {0: 0}
    def r(k):
        if k in memo: return memo[k]    # cache hit
        memo[k] = max(p[i] + r(k - i) for i in range(1, k + 1))
        return memo[k]
    return r(n)

p = [0, 1, 5, 8, 9, 10, 17, 17, 20, 24, 30]
memo_rod(p, 4), memo_rod(p, 7), memo_rod(p, 10)   # (10, 18, 30)

Python's functools.lru_cache does the same with one line. On r(7) its cache_info() reports 8 misses (lengths 0 to 7) and 21 hits: 29 calls in all.

Symptom: RecursionError at n = 5,000.

Measure: the deepest chain is r(n), r(n − 1), …, r(0): n + 1 frames. Python stops at about 1,000.

Fix: fill the answers in a loop from small to large, with no recursion. That is Chapter 2.

With the CLRS prices, what is r(5), the most a 5-inch rod can earn?

Chapter 2

Bottom-Up: Fill the Table Smallest First

Drop the recursion, loop from length 1 upward, and keep a second row that remembers each choice

The memo asks from the top and fills on the way down. Bottom-up DP turns this around. It fills r[0], then r[1], then r[2], and so on. When it reaches r[j], every shorter answer is already in the table. There is no recursion and no stack.

A second row, s[j], keeps the length of the first piece in the best cut of j inches. The values tell you how much. The choices tell you how.

Fill r and s for n = 7

Each step tries one first piece i for the current length j. Purple cells are the ones it reads. Then switch on the wrong order and fill again.

CLRS prices. Ties keep the first piece found, as the loop below does.

Length 7 has a four-way tie. The first pieces 1, 2, 3 and 6 each give $18. The loop keeps the first, so s[7] = 1.

j01234567
r[j]015810131718
s[j]–1232261

To read the cut, follow the choices. s[7] = 1: cut 1 inch, and 6 inches remain. s[6] = 6, so sell the 6 inches whole. The cut is 1 + 6, worth $1 + $17 = $18. The work is 1 + 2 + … + 7 = 28 candidate checks.

Symptom: no crash, but r[7] = 17 and r[5] = 10.

Measure: print the table. Each wrong cell equals the best single-piece price, so every leftover read as 0.

Fix: fill j from 1 up to n. Write every value before you read it.

The fill order changes with the shape of the table. The rule stays the same.

TableA cell readsFill order
1-D (rod)r[0] to r[j − 1]j = 1, 2, …, n
2-D strings (LCS, edit)up, left, up-leftrow by row
Intervals (matrix chain)shorter ranges inside [i, j]by range length
Treethe childrenchildren before parent
The table holds s[5] = 2 and s[3] = 3. How is a 5-inch rod cut, and for how much?

Chapter 3

The Recipe: Two Ingredients, Four Steps

Prove that best answers contain best answers, and find a path problem where they do not

CLRS builds every DP solution in four steps.

  1. Describe the structure of a best solution: which smaller problems it contains.
  2. Write the value recursively: the best value of a problem from the best values of smaller ones.
  3. Compute the values, top-down with a memo or bottom-up with a table.
  4. Build the solution from the stored choices, such as the s row.

Step 1 needs a proof, and it always has the same shape: the cut-and-paste argument. Say the best plan for 7 inches starts with a 1-inch piece. Then its 6-inch leftover must be cut the best way. If a better cut of those 6 inches existed, paste it in. The 7-inch plan would earn more, but it was already the best. So the leftover's plan is best too.

The paste works only if the pieces do not interfere. Here is a problem where they do.

Glue the best subpaths

The question is a path from q to t through r. Solve q to r and r to t on their own, then glue. Switch between shortest and longest.

The graph is CLRS Figure 15.6: edges q–r, q–s, r–t and s–t, each of length 1, usable in both directions.

A simple path never visits a node twice. The longest simple path from q to r is q, s, t, r. The longest from r to t is r, q, s, t. Glued, they visit q, s and t twice, so the result is not a simple path at all. The two subproblems compete for the same nodes. Nobody knows an efficient algorithm for longest simple paths in general.

MethodBest from best parts?Parts repeat?Example
Dynamic programmingyesyes, so store themrod cutting, LCS
Divide and conqueryesno, each part is freshmerge sort
Greedyyesone choice per step, no tableactivity selection

Symptom: a "longest path" DP returns a path that visits a node twice.

Measure: check the answer: no repeated nodes. Brute force on a small graph disagrees.

Fix: the subproblems are not independent, so this is not a DP problem. On a graph with no cycles it is: Chapter 8.

Why does the cut-and-paste argument fail for longest simple paths?

Chapter 4

Matrix-Chain Order: Where to Put the Brackets

Choose the order of a chain of matrix products, and fill a table by the length of each range

You must multiply three matrices. A1 is 10 by 30, A2 is 30 by 5, A3 is 5 by 60. Any order gives the same product. The cost is not the same.

A p-by-q matrix times a q-by-r matrix takes p × q × r scalar multiplications, and gives a p-by-r matrix.

The second costs six times more. A chain of 4 matrices has 5 orders; a chain of 10 has 4,862.

Name the parts. The dimension list p0, p1, …, pn gives every size: matrix Ai is pi−1 by pi. Call the fewest multiplications for the range Ai through Aj m[i, j]. The last product splits the range after some matrix Ak.

Say it aloud

m of i j equals the min over k from i up to j minus one of m of i k, plus m of k plus one j, plus p-i-minus-one times p-k times p-j.

m[i, j]
m of i j the fewest scalar multiplications to compute Ai through Aj. A single matrix costs 0.
mini ≤ k < j
the min over k try every split point k from i to j − 1 and keep the cheapest.
m[i, k]
m of i k the best cost of the left part, Ai through Ak.
m[k+1, j]
m of k plus one j the best cost of the right part, Ak+1 through Aj.
pi−1 pk pj
p-i-minus-one times p-k times p-j the last product: a pi−1-by-pk result times a pk-by-pj result.
In plain words

For each split k, add the best cost of the left part, the best cost of the right part, and the cost of multiplying the two results. The cheapest split gives m of i j.

With numbers

CLRS's first four matrices: p = 30, 35, 15, 5, 10. For m[1, 4], k = 1 gives 0 + 4,375 + 10,500 = 14,875. k = 2 gives 21,000. k = 3 gives 7,875 + 0 + 1,500 = 9,375, the minimum.

Fill the chain table by range length

Pick a chain and step. Each step fills one cell; purple cells are the two parts of its best split.

Chain

The 3-matrix chain is our toy. The 4- and 6-matrix chains are CLRS's (dimensions 30, 35, 15, 5, 10, 20, 25); the 6-matrix answer is 15,125.

m[i, j] reads only shorter ranges, so fill ranges of length 2, then 3, up to n. The loops try (n3 − n)/6 splits: 10 for 4 matrices. Time grows as n3. A second table, s[i, j], keeps each best k and gives the brackets: ((A1(A2A3))A4).

Symptom: always splitting where the last product is cheapest costs 19,500 on the 4-matrix chain.

Measure: compare with the table: 9,375. The cheap last step hid costly work inside the parts.

Fix: score every split by its full cost: both parts plus the last product.

The same shape builds the optimal binary search tree (CLRS 15.5). Users search keys A, B, C 70%, 20% and 10% of the time. B at the root costs 1.8 comparisons per search on average; A at the root costs 1.4.

A1 is 10 by 30, A2 is 30 by 5, A3 is 5 by 60. What is the cheapest cost of A1A2A3?

Chapter 5

Longest Common Subsequence

Find the longest thread two strings share, then walk back through the table to read it

You have two versions of a file. Which lines stayed? A tool like diff answers with a longest common subsequence of the lines.

A subsequence keeps some characters of a string in their order and drops the rest. BCAB is a subsequence of ABCBDAB and of BDCAB. No common subsequence is longer, so it is a longest common subsequence (LCS). A string of m characters has 2m subsequences, so trying them all does not scale.

Name the parts. The strings are X = x1 … xm and Y = y1 … yn. Call the LCS length of the first i characters of X and the first j characters of Y c[i, j].

Say it aloud

c of i j equals c of i minus one, j minus one, plus one, if x-i equals y-j; otherwise the max of c of i minus one j and c of i j minus one.

c[i, j]
c of i j the LCS length of the first i characters of X and the first j of Y. It is 0 when i or j is 0.
xi = yj
x-i equals y-j the last characters of the two prefixes match.
c[i−1, j−1] + 1
c of i minus one, j minus one, plus one the match ends the LCS: drop both characters and add 1.
max(…)
the max of the cell above and the cell to the left no match: drop xi or drop yj, and keep the better.
In plain words

Look at the last characters, x-i and y-j. If they match, take the LCS of both shorter prefixes and add one. If not, one of them is not in the LCS: drop either and keep the longer result.

With numbers

X = ABCBDAB, Y = BDCAB. For c[7, 5]: x7 = B = y5, so c[7, 5] = c[6, 4] + 1 = 3 + 1 = 4. For c[5, 3]: x5 = D and y3 = C differ, so c[5, 3] = max(c[4, 3], c[5, 2]) = max(2, 2) = 2.

Fill the table, then trace back

Pick a pair or type your own. Fill runs row by row; teal cells are matches. Then trace back from the corner.

Pair

Up to 9 characters each. The traceback moves up on a tie, as the code does.

The traceback starts at c[m, n]. On a match it steps diagonally and keeps the character. Otherwise it moves to the larger neighbour, up on a tie. For our pair it keeps B, A, C, B; read backwards that is BCAB. A tie can hide a second answer: BDAB is also an LCS.

The table has (m + 1)(n + 1) cells and each costs one step, so time is m × n. Two rows are enough for the length alone. The traceback needs the full table, unless you use Hirschberg's linear-space method.

Symptom: the corner says length 0, yet the traceback prints CAB.

Measure: check that the output has length c[m, n] and is a subsequence of both strings.

Fix: fill both branches of the cell rule. A traceback is only as good as its table.

What is an LCS of AGGTAB and GXTXAYB?

Chapter 6

Edit Distance: Three Moves and a Free Match

Count the fewest inserts, deletes and replaces between two words, and read the moves off the table

You typed "kitten". The spell checker offers "sitting". How far apart are they? The edit distance, or Levenshtein distance, is the fewest single-character moves that turn one string into the other. There are three moves, each costing 1: insert a character, delete a character, replace a character.

Name the parts. Call the edit distance between the first i characters of X and the first j characters of Y d[i, j]. Turning i characters into nothing takes i deletes, so d[i, 0] = i; likewise d[0, j] = j. The mark [xi ≠ yj] is 1 if the two characters differ and 0 if they match.

Say it aloud

d of i j equals the min of three things: d of i minus one j plus one, d of i j minus one plus one, and d of i minus one, j minus one, plus the mismatch mark.

d[i, j]
d of i j the fewest moves that turn the first i characters of X into the first j of Y.
min
the min keep the cheapest of the three ways to end.
d[i−1, j] + 1
the cell above, plus one end by deleting xi.
d[i, j−1] + 1
the cell to the left, plus one end by inserting yj.
d[i−1, j−1] + [xi ≠ yj]
the diagonal cell, plus the mismatch mark end by replacing xi with yj; free if they already match.
In plain words

The last move is a delete, an insert, or a replace (free on a match). Price each one as the best cost of the smaller problem it leaves plus the move. Keep the cheapest.

With numbers

kitten to sitting, d[6, 7]: delete gives d[5, 7] + 1 = 4 + 1 = 5. Insert gives d[6, 6] + 1 = 2 + 1 = 3. Replace gives d[5, 6] + 1 = 3 + 1 = 4, since n and g differ. So d[6, 7] = 3.

Turn one word into another

Pick a pair or type your own. The warm path is one cheapest way. Each step on it is a match, a replace, an insert or a delete.

Pair

Up to 9 characters each. Ties prefer the diagonal, then delete, then insert.

Read the kitten path from the top-left corner: replace k with s, match i, t, t, replace e with i, match n, insert g. Three paid moves.

Edit distance is close to LCS, but not equal. With inserts and deletes only, the distance is m + n − 2L, where L is the LCS length. For kitten and sitting, L = 4, so that distance is 6 + 7 − 8 = 5. Replace does in one move what costs a delete and an insert, so the true edit distance is 3.

Symptom: the distance from "abc" to "" comes out 0, and horse to ros comes out too small.

Measure: test the borders: d("abc", "") must be 3.

Fix: set the first column to i and the first row to j before the loop.

What is the edit distance from "sunday" to "saturday"?

Chapter 7

The Showcase: Take or Skip

Pack a bag and make change with the same move: for each item, compare taking it with leaving it

You pack a bag that holds 8 kg. Four items lie on the table. Each goes in whole or stays out, so this is the 0/1 knapsack problem.

Item1234
Weight (kg)2345
Value ($)3456

Name the parts. Item i weighs wi and is worth vi. Call the best value you can pack from the first i items into a bag of capacity w K[i, w]. With no items, K[0, w] = 0.

Say it aloud

K of i w equals the max of K of i minus one w, and v-i plus K of i minus one, w minus w-i.

K[i, w]
K of i w the best value, in dollars, from items 1 to i in a bag of w kg.
max
the max keep the better of skipping item i and taking it.
K[i−1, w]
K of i minus one w skip item i: the best from the earlier items, same bag.
vi
v-i the value of item i. You may take it only if wi ≤ w.
K[i−1, w − wi]
K of i minus one, w minus w-i the best from the earlier items in the room item i leaves.
In plain words

Skip item i and keep the best of the earlier items. Or take it: add v-i to the best of the earlier items in w minus w-i kg. Keep the larger.

With numbers

K[4, 8] = max(K[3, 8], 6 + K[3, 3]) = max(9, 6 + 4) = 10. Take item 4 (5 kg) and item 2 (3 kg): exactly 8 kg, $10.

The same move solves coin change: pay an amount with the fewest coins, any number of each coin. The fewest coins for amount a is 1 plus the fewest for a − c, over every coin c that fits. With coins 1, 3 and 4, amount 6 needs 2 coins (3 + 3).

Take or skip, cell by cell

Choose a problem. Step through the cells, or press Play. Blue is the cell now; purple are the cells it reads. At the end the greedy shortcut tries the same task.

8 kg

Items and coin sets are illustrative. Greedy knapsack takes the best value per kg first; greedy change takes the largest coin first.

Greedy loses both games. Packing by value per kg takes items 1 and 2 (1.5 and 1.33 dollars per kg), fills 5 kg for $7, and then nothing else fits. Paying 6 with the largest coin first gives 4 + 1 + 1, three coins. With US coins 1, 5, 10 and 25, greedy matched DP at every amount we tried, 1 to 30.

The table has (n + 1)(W + 1) cells, so the time is n × W. That looks polynomial, but W is a number written in about log2 W bits. A capacity of 109 needs a billion columns. Such a time is called pseudo-polynomial.

Symptom: a one-row knapsack returns $12 for the 8 kg bag.

Measure: $12 is four copies of item 1. The loop over w ran upward, so it read a cell that already held item 1.

Fix: in the one-row version, loop w from W down to wi.

Coins are 1, 3 and 4. What is the fewest number of coins for amount 6, and what does largest-coin-first give?

Chapter 8

Beyond Grids: DP on Trees and DAGs

Plan a party on an org chart with two numbers per person, and see every DP as a walk through a graph

You plan a company party. The org chart is a tree, and each person has a fun rating. One rule: nobody comes if their direct boss comes. Which guest list has the most fun? This is the maximum weight independent set on a tree.

Keep two numbers per person v. Call v's fun rating f(v). Call the best fun in v's part of the tree I(v) if v comes, and E(v) if v stays home. The children of v are the people c who report to v.

Say it aloud

I of v equals f of v plus the sum over children c of E of c. E of v equals the sum over children c of the max of I of c and E of c.

I(v)
I of v the best fun in v's part of the tree if v comes.
f(v)
f of v v's own fun rating.
Σc
the sum over children c add one term for each person who reports to v. A leaf has none, so the sum is 0.
E(c)
E of c the best fun under child c with c at home: forced when v comes.
E(v)
E of v the best fun in v's part of the tree if v stays home.
max(I(c), E(c))
the max of I of c and E of c with v at home, each child picks whichever is better.
In plain words

If v comes, add f of v to each child's E, because the children must stay home. If v stays home, each child takes the larger of its I and its E. Do every child before its boss.

With numbers

Person 3 manages 7 and 2, and 2 manages 5. E(2) = max(5, 0) = 5. So I(3) = 3 + 0 + 5 = 8 and E(3) = max(7, 0) + max(2, 5) = 12.

Climb the party tree

Step the walk, children before parents. Then drag the top boss's fun and watch the guest list.

8

The tree and ratings are illustrative. A tie keeps the boss at home.

At the top boss, I = 8 + 12 + 7 = 27 and E = 12 + 7 = 19. The best party: guests 8, 7, 5, 6 and 1, fun 27. The walk visits each person once, so the time grows with the number of people. On a general graph nobody knows a fast method.

Every DP is a graph of subproblems: each node is a subproblem, each arrow means "reads". The arrows never form a cycle, or a value would depend on itself.

On a graph with no cycles, a DAG, Chapter 3's longest path is easy: no path can return to a node. Take edges A→B 3, A→C 6, B→D 4, B→E 1, C→D 2, C→E 7 and D→E 5. Then dist[D] = max(3 + 4, 6 + 2) = 8 and dist[E] = max(3 + 1, 6 + 7, 8 + 5) = 13.

Symptom: the party code says the best fun is 8, the top boss alone.

Measure: print I and E at each visit. The code visited the boss before any child had values.

Fix: visit in post-order: all children, then the parent.

An org chart has 1,000,000 people. How long does the include/exclude DP take?

Chapter 9

The Field Guide

Keep the recurrences, the numbers, the checks and the code in one place

Every problem here has a subproblem, a choice and a table. The subproblem names a cell. The choice is the recurrence. The time is the number of cells times the work per cell.

ProblemCellTimeNumber to remember
Rod cuttingr(j), j ≤ nn27 inches: $18, cut 1 + 6
Matrix chainm[i, j]n3CLRS 6 matrices: 15,125
Optimal BSTbest tree for keys i..jn370/20/10%: 1.4 against 1.8
LCSc[i, j]m × nABCBDAB, BDCAB: BCAB
Edit distanced[i, j]m × nkitten to sitting: 3
0/1 knapsackK[i, w]n × W8 kg bag: $10, greedy $7
Coin changefewest coins for aamount × coins1, 3, 4 for 6: 2 coins, greedy 3
Tree partyI(v), E(v)nroot I = 27, E = 19

More recurrences of the same shape

Before you trust a DP

  1. Write in one sentence what a cell means, as a comment.
  2. Prove best from best with cut-and-paste. Check the parts do not share resources.
  3. Set the base cases and test them on the smallest inputs.
  4. Fill so you write every cell before you read it.
  5. Keep the choices in a second table, and rebuild the answer from them.
  6. Compare with brute force on small random inputs.
pythondef rod(p, n):                           # p[i] = price of i inches, p[0] = 0
    r, s = [0] * (n + 1), [0] * (n + 1)
    for j in range(1, n + 1):                  # smallest first
        r[j], s[j] = max((p[i] + r[j - i], i) for i in range(1, j + 1))
    return r, s

def lcs_len(X, Y):
    c = [[0] * (len(Y) + 1) for _ in range(len(X) + 1)]
    for i in range(1, len(X) + 1):
        for j in range(1, len(Y) + 1):
            c[i][j] = c[i-1][j-1] + 1 if X[i-1] == Y[j-1] else max(c[i-1][j], c[i][j-1])
    return c[-1][-1]

def knapsack(items, W):                    # items: [(weight, value)]
    K = [0] * (W + 1)
    for w_i, v_i in items:
        for w in range(W, w_i - 1, -1):          # downward: each item once
            K[w] = max(K[w], v_i + K[w - w_i])
    return K[W]

rod([0, 1, 5, 8, 9, 10, 17, 17], 7)[0][7]                 # 18
lcs_len("ABCBDAB", "BDCAB")                       # 4
knapsack([(2, 3), (3, 4), (4, 5), (5, 6)], 8)              # 10

Richard Bellman named the method in the 1950s. "Programming" meant planning with tables, as in linear programming, not writing code.

Keep going

Sources

  1. Cormen, T. H., Leiserson, C. E., Rivest, R. L., and Stein, C. Introduction to Algorithms, 3rd edition, Chapter 15, Dynamic Programming. MIT Press, 2009.
  2. Bellman, R. Dynamic Programming. Princeton University Press, 1957.
  3. Levenshtein, V. I. "Binary codes capable of correcting deletions, insertions, and reversals." Soviet Physics Doklady 10, 1966.
  4. Hirschberg, D. S. "A linear space algorithm for computing maximal common subsequences." Communications of the ACM 18(6), 1975.
The takeaway. Name the cell in one sentence. Then the recurrence, the fill order and the running time follow from it.
Greedy by value per kg is optimal for fractional knapsack but not for 0/1 knapsack. Why?

Now press Present or Teach and explain from memory: why plain recursion makes 2n calls, the memo, the fill order, cut-and-paste, and one table of your choice. Then go back to the hero, set the rod to 30 inches, and say why the memo makes 466 calls where plain recursion makes over a billion.

Dynamic Programming · CLRS Chapter 15
Chapter 13 · Chapter 16 · Back to Gleams