Dynamic programming
| Problem | Optimise a sequence of decisions, or a combinatorial structure that decomposes into overlapping subproblems: knapsack, coin change, sequence alignment, matrix-chain ordering, Markov decision processes |
| Devised by | Richard Bellman (1950s); edit distance: Vladimir Levenshtein (1965), Robert Wagner and Michael Fischer (1974); Markov decision processes: Bellman (1957), Ronald Howard (1960) |
| Accuracy | Exact for the discrete problems; value iteration converges geometrically, with error after iterations for discount |
| Cost | The number of subproblems times the work per subproblem: for knapsack, for edit distance, for matrix chains, per value iteration |
| Read first | Background: what a minimum looks like |
| API | knapsack_01, coin_change_min_coins, edit_distance, longest_common_subsequence, longest_increasing_subsequence, matrix_chain_order, FiniteMdp |
Overview
Many optimisation problems have a recursive structure: the best solution of the whole is built from the best solutions of parts, and the same parts recur many times. Dynamic programming solves each subproblem once, stores its answer in a table, and builds up to the full problem. Where naive recursion or exhaustive search takes exponential time, dynamic programming often takes polynomial time.
The idea applies far beyond the examples here: shortest paths in graphs (Bellman-Ford), the Viterbi algorithm for hidden Markov models, sequence alignment in bioinformatics, parsing, optimal control and reinforcement learning all are dynamic programming.
Where it is used
Dynamic programming solves problems that decompose into overlapping subproblems.
- Sequence comparison. Edit distance underlies spell checkers and DNA sequence alignment; the longest common subsequence is behind
diffin version control. - Resource allocation. The knapsack problem models budgeting, cargo loading and project selection.
- Control and planning. Bellman’s principle gives optimal policies in inventory control and in robot path planning.
- Speech and signals. Dynamic time warping aligns recordings that differ in speed; the Viterbi algorithm is dynamic programming on a trellis.
History
Richard Bellman developed dynamic programming at the RAND Corporation in the early 1950s, for multistage decision problems in logistics and control. He later wrote that he chose the name to shield the mathematical research from a Secretary of Defense who disliked the word “research”: “programming” meant planning, and “dynamic” sounded impressive and could not be used pejoratively. His book Dynamic Programming (1957) stated the principle of optimality and introduced Markov decision processes, for which Ronald Howard (1960) developed policy iteration.
Many of the classic algorithms are dynamic programs found independently in different fields: Vladimir Levenshtein defined the edit distance in 1965 for error-correcting codes, Saul Needleman and Christian Wunsch (1970) aligned protein sequences, and Robert Wagner and Michael Fischer (1974) published the general string-to-string algorithm. Andrew Viterbi’s decoding algorithm (1967) and the matrix-chain algorithm (Godbole, 1973) followed the same pattern.
The idea
Bellman’s principle
Dynamic programming applies to problems that can be solved by a sequence of decisions. Its foundation is an observation about what the best sequence must look like.
Principle of optimality. An optimal policy has the property that, whatever the initial state and initial decision, the remaining decisions must constitute an optimal policy with regard to the state resulting from the first decision.
A route example makes it concrete. If the shortest route from A to C passes through B, then the part of it from B to C must be a shortest route from B to C. If a shorter one existed, splicing it in would shorten the whole route, a contradiction. So the best way to finish does not depend on how we arrived, only on where we are: the state.
This has a practical consequence. Define the value of a state as the best result achievable from it. The value of a state can then be computed from the values of the states one decision later: try each possible decision, add its immediate cost to the value of the state it leads to, and keep the best. Such a recurrence is called a Bellman equation.
Two properties make the recurrence useful.
- Optimal substructure: the principle of optimality holds, so that optimal solutions are assembled from optimal solutions of smaller subproblems.
- Overlapping subproblems: the same subproblems are reached along many different decision paths. A naive recursion would solve them again and again, taking exponential time. Storing each value the first time it is computed, in a table, reduces the work to one computation per distinct subproblem.
The method therefore has three steps: define the subproblems and their recurrence; fill the table from the smallest subproblems upwards; and recover an actual optimal solution, not just its value, by tracing back through the table the choices that achieved each entry.
Sequence and combinatorial problems
The art is in choosing the subproblems. The classic examples show the patterns.
- 0/1 knapsack. Items with weights and values are to be packed into a knapsack of capacity , each item used at most once, to maximise the total value. Let be the best value using only the first items within capacity . Item is either left out, in which case the best is , or put in, which earns and leaves capacity for the earlier items:
The table has entries. That is polynomial in the capacity , but can be exponentially large in the number of digits needed to write it down, and the problem is in fact NP-hard.
- Coin change. Find the fewest coins that make an amount . The last coin is one of the denominations , and the rest must be the fewest coins for : . The obvious greedy method, always taking the largest coin that fits, can fail: for coins and amount 6 it takes , three coins, while the recurrence finds .
- Edit distance. The fewest single-character insertions, deletions and substitutions that turn string into string . Let be the distance between the first characters of and the first of . Look at the last characters: either is deleted, or is inserted, or is matched with (free if they are equal, one substitution if not):
where is 1 if the characters differ and 0 otherwise.
- Longest common subsequence. The same table, with matches scoring 1 and no substitutions.
- Longest increasing subsequence. An refinement that keeps, for each length, the smallest possible last element of an increasing subsequence of that length (“patience sorting”).
- Matrix-chain ordering. The cheapest order in which to multiply . The subproblems are the contiguous subchains; the cost of a chain is the minimum over the place of the last multiplication. There are subchains and split points each: .
Table 5.11. Dynamic programming examples.
| problem | input | result |
|---|---|---|
| 0/1 knapsack | weights 12, 2, 1, 1, 4; values 4, 2, 1, 2, 10; capacity 15 | value 15, items (1, 2, 3, 4) |
| fewest coins | coins 1, 5, 10, 25; amount 63 | 6 coins: (3, 0, 1, 2) of each |
| fewest coins | coins 1, 3, 4; amount 6 (greedy takes 4 + 1 + 1) | 2 coins: (0, 2, 0) of each |
| edit distance | kitten → sitting | 3 |
| longest common subsequence | ABCBDAB, BDCABA | BCBA |
| longest increasing subsequence | 3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 | (1, 2, 3, 5, 7, 9) |
| matrix-chain order | dimensions 30, 35, 15, 5, 10, 20, 25 | 15125 multiplications: ((A0(A1A2))((A3A4)A5)) |
Markov decision processes
The same idea handles decisions whose outcomes are uncertain. A Markov decision process (MDP) consists of
- a set of states ;
- a set of actions available in each state;
- a reward for taking action in state ;
- transition probabilities : the probability that the action leads to state .
A policy is a rule that chooses an action in each state. Its value is the expected total reward, with rewards steps in the future weighted by : . The discount factor makes distant rewards count for less, and keeps the infinite sum finite.
Let be the best achievable value starting from state . The principle of optimality gives its Bellman equation. Taking action earns now, and then the process moves to some state , from which the best continuation is worth , discounted by one step and averaged over where we might land:
The optimal policy takes the maximising action in each state.
Unlike the tables of the previous section, this equation cannot be filled in order, because appears on both sides: states can lead back to each other. Value iteration solves it by repeated substitution. Start from , evaluate the right-hand side to get a new , and repeat. This converges because the right-hand side is a contraction: applying it to two different value functions brings them closer together, by the factor in the maximum norm. The distance to the fixed point therefore shrinks by per iteration, so the error falls like :
Figure 5.11. Value iteration.
With (rewards a hundred steps ahead still matter), thousands of iterations are needed. Policy iteration alternates two steps: compute the value of the current policy exactly, by solving a linear system, and then improve the policy by choosing the maximising action in each state. It converges in far fewer, more expensive, iterations. For a finite horizon of steps, there is no circularity: backward induction computes the optimal values stage by stage from the end, exactly, in steps.
Algorithm
The table problems all follow one pattern.
- Allocate a table with one entry for each subproblem, and fill in the trivial ones (no items, an empty string, amount zero).
- Fill the remaining entries in an order in which every entry is computed after the entries it depends on: row by row for knapsack, edit distance and the longest common subsequence; by increasing amount for coin change; by increasing chain length for matrix chains. Each entry takes the best over the choices in its recurrence.
- Read off the optimal value from the last entry.
- Trace back to recover a solution. Starting at the last entry, find which choice achieved its value (by storing the choice when the entry was filled, or by re-testing the recurrence), record it, move to the entry that choice came from, and continue to a trivial entry.
The cost is the number of entries times the number of choices per entry: for knapsack, for edit distance, for matrix chains.
Value iteration for a discounted Markov decision process:
- start with for every state;
- compute for every state;
- if the largest change is below , stop; otherwise replace by and go to 2;
- return and the policy that takes the maximising action in each state.
The threshold in step 3 is chosen so that the returned policy’s value is within the tolerance of the optimum. One sweep costs for states and actions.
Backward induction for a horizon of steps: set the values after the last step to zero, and apply step 2 (without discounting, if none is wanted) times, storing the maximising action for each state at each stage.
Implementation
let mut best = vec![vec![0.0f64; capacity + 1]; n + 1];
for i in 1..=n {
for w in 0..=capacity {
best[i][w] = best[i - 1][w];
if weights[i - 1] <= w {
best[i][w] = best[i][w].max(best[i - 1][w - weights[i - 1]] + values[i - 1]);
}
}
}
let mut chosen = Vec::new();
let mut w = capacity;
for i in (1..=n).rev() {
if best[i][w] != best[i - 1][w] {
chosen.push(i - 1);
w -= weights[i - 1];
}
}
chosen.reverse();
Ok((best[n][capacity], chosen))
let mut values = vec![0.0; self.rewards.len()];
for _ in 0..max_iterations {
let sol = self.greedy(&values, discount);
let change = sol.values.iter().zip(&values).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
values = sol.values;
// Standard stopping rule guaranteeing the value error is below `tolerance`.
if change <= tolerance * (1.0 - discount) / (2.0 * discount).max(1e-12) {
return Ok(self.greedy(&values, discount));
}
}
Err(ErrorsJSL::RuntimeError("Value iteration did not converge."))
- Each sequence function returns the optimal value together with one optimal solution (chosen items, coin counts, matched index pairs, an edit script, a parenthesisation).
FiniteMdp::validatechecks that the transition probabilities of every action sum to 1;backward_induction,value_iterationandevaluate_policysolve finite-horizon, discounted and fixed-policy problems.- The tables are dense: knapsack needs numbers, so very large capacities are impractical.
In practice
//! Dynamic programming: sequence problems and a Markov decision process.
//!
//! Run with `cargo run -p lib_jsl_optimization --example optimization_dynamic_programming`.
use lib_jsl_optimization::dynamic_programming::{FiniteMdp, edit_distance, knapsack_01};
fn main() {
let (value, items) = knapsack_01(&[5, 4, 6, 3], &[10.0, 40.0, 30.0, 50.0], 10).unwrap();
println!("knapsack: value {value} from items {items:?}");
let (d, script) = edit_distance(b"intention", b"execution");
println!("edit distance intention → execution: {d} ({} operations in the script)", script.len());
// A machine that is good (state 0) or worn (state 1). Running it earns 10 when good and 4
// when worn, and a good machine wears out with probability 0.3; repairing costs 6 (earning
// −6 for the period) and restores it. Discount 0.9 per period.
let mdp = FiniteMdp {
transitions: vec![
vec![vec![(0, 0.7), (1, 0.3)], vec![(0, 1.0)]],
vec![vec![(1, 1.0)], vec![(0, 1.0)]],
],
rewards: vec![vec![10.0, -6.0], vec![4.0, -6.0]],
};
let solution = mdp.value_iteration(0.9, 1e-10, 10_000).unwrap();
let names = ["run", "repair"];
println!("good: {} (value {:.3}); worn: {} (value {:.3})", names[solution.policy[0]], solution.values[0], names[solution.policy[1]], solution.values[1]);
}
Strengths
- Exact optimal solutions to problems that look exponential.
- A single principle covers sequence alignment, scheduling, control and decision-making under uncertainty.
Weaknesses
- The table can be enormous (the “curse of dimensionality”, Bellman’s own phrase), which limits dynamic programming to problems with a small state space.
- Each problem needs its own formulation; finding the right subproblems is the hard part.
Exercises
- Show that the greedy method (largest coin first) is optimal for coins but not for .
- Modify the edit distance to give substitutions cost 2. What does the distance then count?
- Count the parenthesisations of a chain of matrices (the Catalan numbers) and compare with the cost of the dynamic program.
- Prove that the Bellman operator is a contraction with factor in the maximum norm.
- Implement policy iteration for
FiniteMdpusingevaluate_policy, and compare its iterations with value iteration for .
Hints and answers
- For and the amount 6, greedy gives (three coins) while uses two. For greedy is optimal (the system is canonical); verify it by comparing greedy with the dynamic program for every amount up to 100.
- A substitution then costs the same as a deletion plus an insertion, so it is never worth using, and the distance becomes : it counts the characters that must be deleted from one string and inserted into the other, the length of the longest common subsequence being the part kept.
- The number of ways to parenthesise a chain of matrices is the Catalan number , exponential, while the dynamic program takes because it solves each of the subchains once, trying split points.
- For value functions , , so .
- Policy iteration usually converges in a handful of iterations because each evaluation is exact, while value iteration needs of the order of sweeps, hundreds when .
Further reading
- R. Bellman, Dynamic Programming, Princeton University Press, 1957 (Dover reprint, 2003).
- T. H. Cormen, C. E. Leiserson, R. L. Rivest and C. Stein, Introduction to Algorithms, 4th ed., MIT Press, 2022, chapter 14.
- R. A. Wagner and M. J. Fischer, “The string-to-string correction problem”, Journal of the ACM 21 (1974) 168–173.
- M. L. Puterman, Markov Decision Processes, Wiley, 1994.
- R. S. Sutton and A. G. Barto, Reinforcement Learning: An Introduction, 2nd ed., MIT Press, 2018, chapter 4.