Chapter 8 · Dynamic Programming

DP Table Studio

Dynamic Programming (DP) solves each small subproblem once, writes the answer in a table, and builds bigger answers from smaller ones. Pick a problem, watch every cell read the cells it depends on, then trace back through the table to recover the actual choices.

predictions: 0 / 0

 
cell being filled cells it reads winning choice (arrow) losing choice (dashed arrow) traceback / optimal answer retrieved, not recomputed never computed / blocked

How to read this

  • The grid is the DP table. Row and column headers show what each index means (an amount, a capacity, a character, an item with its weight and value).
  • The blue cell is being filled right now. The yellow cells are the smaller subproblems it reads. Arrows point from those cells into the new one: the solid orange arrow is the option that won the max/min, dashed grey arrows are options that lost.
  • The formula strip under the table plugs the real numbers into the recurrence, so you can check the arithmetic yourself.
  • After the table is full, the green traceback walks backwards from the goal cell and recovers the choices (coins, items, path, common letters, or edit operations).
  • Memory-function mode: purple cells were looked up instead of recomputed; grey “—” cells were never needed at all.

Try this

  1. Coin-row: load 5, 1, 2, 10, 6, 2. Before playing, guess the best total. (Expect F = 0, 5, 5, 7, 15, 15, 17 and coins 5 + 10 + 2.)
  2. Change-making: coins 1, 3, 4, amount 6. A greedy cashier gives 4 + 1 + 1; watch the table find 3 + 3 (F[6] = 2). Then try coins 2, 5: which amounts stay ∞?
  3. Knapsack vs memory function: run the W = 5 example both ways. Bottom-up fills all 20 inner cells; the memory function computes only 11 and looks up F[1, 2] once. Where are the “—” cells?
  4. Robot: click board cells to add coins or walls (click cycles empty → coin → wall). Can you build a board with a unique optimal path? One where walls make the goal unreachable?
  5. Edit distance: KITTEN → SITTING needs 3 operations. Turn on 🤔 Predict and fill the table yourself; the score chip tracks how many cells you got right.

Go deeper