The DP method & rod cutting
◈ 5 cardsThe two ingredients of DP, the four-step method, and rod cutting as the canonical example — value + reconstruction.
Why dynamic programming
Dynamic programming (DP) solves an optimization problem by combining solutions to overlapping subproblems, storing each subproblem's answer in a table so it is computed only once. ("Programming" here means a tabular method, as in linear programming — it predates writing code.)
DP applies exactly when a problem has two ingredients:
- Optimal substructure — an optimal solution to the whole problem contains optimal solutions to its subproblems.
- Overlapping subproblems — a naive recursion solves the same subproblems again and again.
When both hold, DP turns an exponential recursion into a polynomial table fill. Merge sort has neither — its left/right halves never overlap — so memoizing it buys nothing.
The four-step method (memorize this)
- Characterize the structure of an optimal solution (find the optimal substructure).
- Recursively define the value of an optimal solution (write the recurrence).
- Compute that value bottom-up, filling a table.
- Reconstruct an optimal solution from stored choices (optional — only if you need which choices, not just the value).
Worked example: rod cutting
A rod of length can be cut into integer pieces; a piece of length sells for price . Maximize total revenue .
Step 1 — substructure. An optimal cut makes a first piece of length (revenue ) and then cuts the remaining length optimally. If the remainder were cut suboptimally we could swap in the better cut for more revenue — contradiction. So:
Step 2 — recurrence.
There are only distinct subproblems () but the naive recursion CUT-ROD calls itself times — that overlap is what DP eliminates.
Step 3 — bottom-up table. Fill in order of increasing length. Each tries all first cuts, so the work is .
Step 4 — reconstruct. Keep a second array = the first-cut length that achieved . To list the cuts: print , set , repeat until . The value table alone cannot tell you which cut won — you need the stored-choice array.
Top-down memoization (recurse, but check the table first) gets the same ; bottom-up just has a smaller constant (no recursion stack).