Skip to main content

Dynamic Programming: Classic Problems

19 min readRead first: The Dynamic Programming Method

This lesson applies the design steps of dynamic programming to several classic problems: counting combinations, the 0/1 knapsack problem, the change with any coin system, the cheapest travel on a river, and two problems on strings, the longest common subsequence and the edit distance. The implementations of the course examples are in the course repository.

What you will learn in this lesson
  • How to turn a recursive formula with overlapping subproblems into a table: Pascal's triangle.
  • How to solve the 0/1 knapsack problem optimally, fill its table by hand and recover which objects to take.
  • What a pseudo-polynomial algorithm is.
  • Two classic dynamic programming algorithms on strings: LCS and edit distance.

Combinations​

In mathematics, a combination is a way of selecting kk things out of a larger group of nn, where (unlike permutations) the order does not matter. For example, given three fruits (an apple, an orange and a pear), there are three combinations of two: apple and orange, apple and pear, and orange and pear. The number of combinations is the binomial coefficient:

C(n,k)=(nk)=n!k! (n−k)!C(n, k) = \binom{n}{k} = \frac{n!}{k!\,(n-k)!}

Computing it with factorials is risky: n!n! overflows a long for n>20n \gt 20, even when the result is small. A better way uses the recurrence behind Pascal's triangle:

C(n,k)={1if k=0 or k=nC(n−1,k−1)+C(n−1,k)if 0<k<nC(n, k) = \begin{cases} 1 & \text{if } k = 0 \text{ or } k = n \\ C(n-1, k-1) + C(n-1, k) & \text{if } 0 \lt k \lt n \end{cases}

(either a given element is in the selection, and we choose the other k−1k - 1 among the remaining n−1n - 1; or it is not, and we choose all kk among the remaining n−1n - 1).

🧠 Checkpoint: Combinations of 9 elements taken 5 at a time

Question: How many combinations of 9 elements taken 5 at a time are there?

Answer: C(9,5)=9!5! 4!=9⋅8⋅7⋅64⋅3⋅2⋅1=126C(9, 5) = \frac{9!}{5!\,4!} = \frac{9 \cdot 8 \cdot 7 \cdot 6}{4 \cdot 3 \cdot 2 \cdot 1} = 126.

Divide and conquer: exponential​

The recurrence translates directly into a recursive method:

public long combinationsRecursive(int n, int k) {
if (k == 0 || k == n) return 1;
return combinationsRecursive(n - 1, k - 1) + combinationsRecursive(n - 1, k);
}

It has the same problem as Fibonacci: the same subproblems are solved many times. Since every call ends in a base case that returns 1, and the result is the sum of those 1s, computing C(n,k)C(n, k) requires 2 C(n,k)−12\,C(n, k) - 1 calls. We measured it:

C(n,k)C(n, k)ValueRecursive callsRecursive timeDynamic programming time
C(20,10)C(20, 10)184,756369,5112 ms0.3 ms
C(26,13)C(26, 13)10,400,60020,801,19947 ms0.04 ms
C(30,15)C(30, 15)155,117,520310,235,039581 ms0.1 ms
C(32,16)C(32, 16)601,080,3901,202,160,7792,317 ms0.07 ms

Dynamic programming: Pascal's triangle​

The different subproblems are the values C(i,j)C(i, j) with 0≤i≤n0 \le i \le n and 0≤j≤min⁡(i,k)0 \le j \le \min(i, k). Store them in a table, filled row by row, from top to bottom: each cell is the sum of the cell above and the cell above-left.

public long combinationsDP(int n, int k) {
long[][] table = new long[n + 1][k + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= Math.min(i, k); j++) {
if (j == 0 || j == i)
table[i][j] = 1; // borders of the triangle
else
table[i][j] = table[i - 1][j - 1] + table[i - 1][j]; // Pascal's rule
}
}
return table[n][k];
}

The first rows of the table (Pascal's triangle):

ii \ jj012345
01
111
2121
31331
414641
515101051
6161520156
Pascal's triangle as a table: C(6, 3) = 20 is the sum of the cell above, 10, and the cell above-left, 1001234560111121213133141464151510105161615201561column j · row iC(i, j) = C(i − 1, j − 1) + C(i − 1, j): row by row, from top to bottom
Each cell of the table is the sum of two cells of the previous row, already computed: for example, C(6, 3) = 10 + 10 = 20.

Complexity. There are O(n⋅k)O(n \cdot k) cells, each computed with one addition: O(n⋅k)O(n \cdot k) time and memory (or O(k)O(k) memory keeping only the previous row). Compare with the exponential growth of the recursive version.

ProofPascal's rule

The 0/1 Knapsack Problem​

We met the knapsack problem in the greedy chapter. Now the objects cannot be fragmented: each object is either taken entirely or left. We have nn objects, each with a weight wiw_i and a value viv_i, and a backpack that can carry a total weight not exceeding WW; we want to maximize the total value. We saw that no greedy heuristic is optimal for this version. Dynamic programming is.

Data​

Three objects and a weight limit W=10W = 10:

Object123
Weight wiw_i655
Value viv_i855

The greedy algorithm by value per weight would take object 1 (ratio 8/6≈1.338/6 \approx 1.33, versus 1 for the others), and then nothing else fits: value 8. Can we do better?

The subproblems and the recurrence​

Subproblems: let V(i,j)V(i, j) be the maximum value we can carry using only the first ii objects, with a weight limit jj. The solution of the problem is V(n,W)V(n, W), here V(3,10)V(3, 10).

Recurrence: for object ii there are only two options: leave it, or take it (if it fits). If we leave it, the best is V(i−1,j)V(i-1, j). If we take it, we gain viv_i, and the remaining capacity j−wij - w_i must be used in the best possible way with the first i−1i - 1 objects (the principle of optimality): V(i−1,j−wi)+viV(i-1, j - w_i) + v_i. Hence:

V(i,j)={−∞if j<00if i=0 and j≥0max⁡(V(i−1,j),  V(i−1,j−wi)+vi)otherwiseV(i, j) = \begin{cases} -\infty & \text{if } j \lt 0 \\ 0 & \text{if } i = 0 \text{ and } j \ge 0 \\ \max\big(V(i-1, j),\; V(i-1, j - w_i) + v_i\big) & \text{otherwise} \end{cases}

The value −∞-\infty for a negative capacity simply means that an object that does not fit can never be taken.

ProofThe 0/1 knapsack recurrence is correct

Filling the table​

The table has a row for each number of objects ii (from 0 to nn) and a column for each weight limit jj (from 0 to WW). It is filled row by row, since each row only depends on the previous one:

ii \ jj012345678910
0 (no objects)00000000000
1 (object 1: w=6,v=8w=6, v=8)00000088888
2 (object 2: w=5,v=5w=5, v=5)00000588888
3 (object 3: w=5,v=5w=5, v=5)000005888810

Some cells, step by step:

  • V(1,6)=max⁡(V(0,6),V(0,0)+8)=max⁡(0,8)=8V(1, 6) = \max(V(0, 6), V(0, 0) + 8) = \max(0, 8) = 8: with capacity 6, object 1 fits.
  • V(2,5)=max⁡(V(1,5),V(1,0)+5)=max⁡(0,5)=5V(2, 5) = \max(V(1, 5), V(1, 0) + 5) = \max(0, 5) = 5: with capacity 5, only object 2 fits.
  • V(2,10)=max⁡(V(1,10),V(1,5)+5)=max⁡(8,5)=8V(2, 10) = \max(V(1, 10), V(1, 5) + 5) = \max(8, 5) = 8: objects 1 and 2 together weigh 11, so the best is object 1 alone.
  • V(3,10)=max⁡(V(2,10),V(2,5)+5)=max⁡(8,10)=V(3, 10) = \max(V(2, 10), V(2, 5) + 5) = \max(8, 10) = 10: taking object 3 and using the remaining capacity 5 in the best way (object 2) beats object 1.

The optimal value is 10, better than the 8 of the greedy algorithm.

Recovering the objects​

The table gives the optimal value. To know which objects to take, trace back from V(n,W)V(n, W): if V(i,j)≠V(i−1,j)V(i, j) \ne V(i-1, j), object ii was taken, so continue from V(i−1,j−wi)V(i-1, j - w_i); otherwise, it was not, so continue from V(i−1,j)V(i-1, j).

  • V(3,10)=10≠V(2,10)=8V(3, 10) = 10 \ne V(2, 10) = 8: object 3 is taken; continue from V(2,5)V(2, 5).
  • V(2,5)=5≠V(1,5)=0V(2, 5) = 5 \ne V(1, 5) = 0: object 2 is taken; continue from V(1,0)V(1, 0).
  • V(1,0)=0=V(0,0)V(1, 0) = 0 = V(0, 0): object 1 is not taken.

Solution: objects 2 and 3, with total weight 10 and value 10.

The 0/1 knapsack table: V(3, 10) is computed from V(2, 10) and V(2, 5); the traceback finds objects 3 and 20123456789100000000000001 (w 6, v 8)000000888882 (w 5, v 5)000005888883 (w 5, v 5)000005888810capacity jleave object 3:V(2, 10) = 8take object 3:V(2, 5) + 5 = 10orange path: the traceback; each diagonal step takes an object (3, then 2), the vertical step leaves object 1V(i, j) = max( V(i − 1, j), V(i − 1, j − wᵢ) + vᵢ )
The table of the example. V(3, 10) chooses between leaving object 3 (the cell above, 8) and taking it (V(2, 5) + 5 = 10). The orange path is the traceback that recovers the objects.
int knapsack01(int maxWeight, int[] weights, int[] values) {
int n = weights.length;
int[][] v = new int[n + 1][maxWeight + 1]; // row 0: no objects, all zeros
for (int i = 1; i <= n; i++)
for (int j = 0; j <= maxWeight; j++) {
v[i][j] = v[i - 1][j]; // leave object i
if (weights[i - 1] <= j) // take it, if it fits
v[i][j] = Math.max(v[i][j], v[i - 1][j - weights[i - 1]] + values[i - 1]);
}
return v[n][maxWeight];
}
🧠 Checkpoint: Fill a table yourself

Question: Four objects with weights 3, 2, 1, 4 and values 6, 4, 5, 10. What is the maximum value with W=6W = 6?

Answer: 15. Several combinations reach it: objects 1, 2 and 3 (weights 3+2+1=63 + 2 + 1 = 6, values 6+4+5=156 + 4 + 5 = 15), or objects 3 and 4 (weights 1+4=51 + 4 = 5, values 5+10=155 + 10 = 15). Fill the 5×75 \times 7 table to check it.

Complexity: pseudo-polynomial​

The table has (n+1)×(W+1)(n + 1) \times (W + 1) cells, each computed in constant time: O(n⋅W)O(n \cdot W) in time and memory (memory can be reduced to O(W)O(W) by keeping a single row, at the cost of not being able to reconstruct the objects).

This looks polynomial, but it depends on the value of WW, not on its size. WW is written with about log⁡2W\log_2 W bits, so O(n⋅W)O(n \cdot W) is exponential in the size of the input, just like the naive greatest common divisor of the divide and conquer chapter. Such algorithms are called pseudo-polynomial: excellent when WW is moderate (a few thousand), impractical when WW is huge (for example, weights in grams of a cargo ship). No algorithm that is polynomial in the size of the input is known for the 0/1 knapsack problem.


The Problem of the Change​

In the greedy chapter we saw that always taking the largest coin that fits gives the fewest coins for the euro, but fails for other coin systems. Dynamic programming solves the problem for any coin system.

Problem. Pay an amount AA with the fewest possible coins, choosing from nn coin values c1<c2<⋯<cnc_1 \lt c_2 \lt \dots \lt c_n, with an unlimited supply of each. We assume c1=1c_1 = 1, so that every amount can be paid.

The subproblems and the recurrence​

Subproblems: let C(i,j)C(i, j) be the minimum number of coins needed to pay the amount jj using only the first ii coin values. The answer is C(n,A)C(n, A).

Recurrence: for coin value cic_i there are two options. Either we do not use it, and the best is C(i−1,j)C(i-1, j); or we use at least one coin of value cic_i, and then we still have to pay j−cij - c_i, possibly with more coins of the same value, so the best is 1+C(i,j−ci)1 + C(i, j - c_i). The difference with the knapsack is in that last term: it stays in the same row ii, because a coin can be used many times.

C(i,j)={jif i=1 (only coins of value 1)C(i−1,j)if i>1 and j<cimin⁡(C(i−1,j),  1+C(i,j−ci))otherwiseC(i, j) = \begin{cases} j & \text{if } i = 1 \text{ (only coins of value 1)} \\ C(i-1, j) & \text{if } i \gt 1 \text{ and } j \lt c_i \\ \min\big(C(i-1, j),\; 1 + C(i, j - c_i)\big) & \text{otherwise} \end{cases}

Filling the table​

With coins of 1, 4, 5 and 12 and A=15A = 15, the table has one row per coin value and one column per amount from 0 to 15. Each row is filled from left to right, because each cell may use the cell cic_i positions to its left in the same row:

Coins \ Amount0123456789101112131415
up to 10123456789101112131415
up to 40123123423453456
up to 50123112322233333
up to 120123112322231233

The answer is 3 coins. To know which ones, walk back from the last cell: if a cell equals the one above it, the coin of its row was not needed, so move up; otherwise one coin of its row was used, so subtract its value and move left. From C(4,15)=C(3,15)=3C(4, 15) = C(3, 15) = 3 we move up, and in row "up to 5" we take three coins of 5: 5 + 5 + 5. The greedy algorithm would take 12 + 1 + 1 + 1, four coins.

The change table for coins 1, 4, 5 and 12: the traceback from C(4, 15) finds 5 + 5 + 50123456789101112131415up to 10123456789101112131415up to 40123123423453456up to 50123112322233333up to 120123112322231233equal to the cell above: coin 12 not needed, move up · then three coins of 5: each one moves 5 columns leftC(i, j) = min( C(i − 1, j), 1 + C(i, j − cᵢ) ): the second term stays in the same row
The traceback in the change table. C(4, 15) equals the cell above, so the 12 is not used; in the row of the 5, each step to the left by 5 columns is one coin: 5 + 5 + 5.
public int change(int amount, int[] coins) { // coins sorted, coins[0] == 1
int n = coins.length;
int[][] c = new int[n][amount + 1];
for (int j = 0; j <= amount; j++)
c[0][j] = j; // only coins of value 1
for (int i = 1; i < n; i++)
for (int j = 0; j <= amount; j++) {
c[i][j] = c[i - 1][j]; // do not use coins[i]
if (j >= coins[i])
c[i][j] = Math.min(c[i][j], 1 + c[i][j - coins[i]]); // use it once more
}
return c[n - 1][amount];
}

Complexity. The table has n×(A+1)n \times (A + 1) cells, each filled in O(1)O(1): O(n⋅A)O(n \cdot A) time and memory. As in the knapsack, it is pseudo-polynomial: it depends on the value of AA. Only the previous row is needed, so the memory can be reduced to a single array of A+1A + 1 positions.

With the table it is easy to check where the greedy algorithm fails: for the coins 1, 4, 5, 12, 20 and 50, it gives more coins than necessary for 10 of the amounts from 1 to 100, the first ones being 8 (greedy 5 + 1 + 1 + 1, optimal 4 + 4) and 15.


Cheaper Travel on the River​

A river has nn docks, numbered from 0 (upstream) to n−1n - 1 (downstream). At each one you can rent a boat to go to any other dock downstream; going upstream is impossible. A table of fees T(i,j)T(i, j) gives the price of a trip from dock ii to dock jj, for i<ji \lt j. A direct trip may cost more than a combination of shorter trips, changing boats at an intermediate dock. We want the minimum cost C(i,j)C(i, j) for every pair of docks i<ji \lt j.

The subproblems and the recurrence​

The cheapest way from ii to jj either goes directly, or stops for the first time at some dock kk between them; then it must continue from kk to jj in the cheapest way, and also reach kk from ii in the cheapest way (the principle of optimality):

C(i,j)=min⁡(T(i,j),  min⁡i<k<j(C(i,k)+C(k,j))),C(i,i)=0C(i, j) = \min\Big( T(i, j),\; \min_{i \lt k \lt j} \big( C(i, k) + C(k, j) \big) \Big), \qquad C(i, i) = 0

Each C(i,j)C(i, j) depends on pairs that are closer together, so the table can be filled by increasing distance j−ij - i, or, as in the code below, with ii going from the last dock upwards and jj from i+1i + 1 downstream.

An example​

With five docks and these fees (only the upper triangle makes sense):

From \ To1234
0381220
14715
229
34

the table of minimum costs is:

From \ To1234
037913
14610
226
34
Five docks on a river with the fee of each trip downstream; the cheapest trip from 0 to 4 costs 13381220471529401234upstreamdownstreamgreen: 3 + 4 + 2 + 4 = 13 · red: direct trip, 20
The five docks of the example and the fee of every trip downstream. The cheapest way from dock 0 to dock 4 changes boat at every dock and costs 13, instead of the direct fee of 20.

For example, C(2,4)=min⁡(9,C(2,3)+C(3,4))=min⁡(9,2+4)=6C(2, 4) = \min(9, C(2, 3) + C(3, 4)) = \min(9, 2 + 4) = 6, and the cheapest trip from the first to the last dock costs 13 instead of the direct fee of 20, stopping at every dock: 3+4+2+43 + 4 + 2 + 4. Storing, for each pair, the dock kk that gave the minimum allows recovering the route.

public int[][] minimumCosts(int[][] fee) {
int n = fee.length;
int[][] cost = new int[n][n];
for (int i = n - 2; i >= 0; i--)
for (int j = i + 1; j < n; j++) {
int best = fee[i][j]; // direct trip
for (int k = i + 1; k < j; k++) // first stop at k
best = Math.min(best, cost[i][k] + cost[k][j]);
cost[i][j] = best;
}
return cost;
}

Complexity. There are about n2/2n^2 / 2 pairs, and each one tries up to nn intermediate docks: O(n3)O(n^3) time and O(n2)O(n^2) memory. It is the same idea as Floyd's algorithm (Floyd, 1962) for shortest paths between all pairs of nodes of a graph, simplified by the fact that the boats only go downstream.


Beyond the Course: Dynamic Programming on Strings​

Two classic problems show how dynamic programming handles sequences.

Longest common subsequence (LCS)​

A subsequence of a string is obtained by deleting some characters without changing the order of the rest. The longest common subsequence of two strings is the longest string that is a subsequence of both. For example, for ALGORITHM and ALTRUISM, an LCS is ALRIM, of length 5.

The longest common subsequence of ALGORITHM and ALTRUISM: ALRIMALGORITHMALTRUISMALRIM: length 5
A longest common subsequence of ALGORITHM and ALTRUISM: the five matched letters keep their order in both strings, and the lines never cross.

Subproblems: L(i,j)L(i, j) = length of the LCS of the first ii characters of aa and the first jj characters of bb.

L(i,j)={0if i=0 or j=0L(i−1,j−1)+1if ai=bjmax⁡(L(i−1,j),  L(i,j−1))otherwiseL(i, j) = \begin{cases} 0 & \text{if } i = 0 \text{ or } j = 0 \\ L(i-1, j-1) + 1 & \text{if } a_i = b_j \\ \max\big(L(i-1, j),\; L(i, j-1)\big) & \text{otherwise} \end{cases}

If the last characters match, they are part of the LCS; otherwise, one of them is not, and we keep the best of discarding either one. The table has (∣a∣+1)×(∣b∣+1)(|a| + 1) \times (|b| + 1) cells: O(∣a∣⋅∣b∣)O(|a| \cdot |b|). The diff tool that compares versions of a file is based on this idea, applied to lines instead of characters.

ProofThe LCS recurrence is correct

Edit distance​

The edit distance (or Levenshtein distance) between two strings is the minimum number of single-character insertions, deletions and substitutions needed to transform one into the other. For example, KITTEN → SITTING needs 3 operations: substitute K by S, substitute E by I, insert G.

Transforming KITTEN into SITTING with three operations: two substitutions and one insertionKITTENSITTINGKSsubst.IIkeepTTkeepTTkeepEIsubst.NNkeep–Ginsert3 operations
An optimal alignment of KITTEN and SITTING: two substitutions and one insertion, edit distance 3.
D(i,j)=min⁡{D(i−1,j)+1(delete ai)D(i,j−1)+1(insert bj)D(i−1,j−1)+(ai≠bj ? 1:0)(substitute, or keep if equal)D(i, j) = \min \begin{cases} D(i-1, j) + 1 & \text{(delete } a_i\text{)} \\ D(i, j-1) + 1 & \text{(insert } b_j\text{)} \\ D(i-1, j-1) + (a_i \ne b_j\ ?\ 1 : 0) & \text{(substitute, or keep if equal)} \end{cases}

with D(i,0)=iD(i, 0) = i and D(0,j)=jD(0, j) = j. The complete table for KITTEN (rows) and SITTING (columns):

∅SITTING
∅01234567
K11234567
I22123456
T33212345
T44321234
E55432234
N66543323

Spelling correctors use it to suggest the closest dictionary words, and bioinformatics uses weighted variants to align DNA sequences.

Common mistakes
  • Calling O(n⋅W)O(n \cdot W) polynomial. It is pseudo-polynomial: WW is a value, exponential in its number of digits.
  • Using the previous row when coins are unlimited. In the change problem, using one more coin of the same value stays in the same row.
  • Computing only the optimal value. To give the solution, keep the table (or the decisions) and reconstruct it backwards.
  • Mixing string indices and table indices. L(i,j)L(i, j) refers to prefixes of lengths ii and jj, so character ii is at position i−1i - 1.

Summary​

ProblemSubproblemsRecurrence (idea)Complexity
FibonacciF(i)F(i), 0≤i≤n0 \le i \le nF(i)=F(i−1)+F(i−2)F(i) = F(i-1) + F(i-2)O(n)O(n)
CombinationsC(i,j)C(i, j)C(i,j)=C(i−1,j−1)+C(i−1,j)C(i, j) = C(i-1, j-1) + C(i-1, j)O(n⋅k)O(n \cdot k)
0/1 knapsackV(i,j)V(i, j): first ii objects, capacity jjleave or take object iiO(n⋅W)O(n \cdot W), pseudo-polynomial
ChangeC(i,j)C(i, j): first ii coin values, amount jjskip coin ii, or use one more (same row)O(n⋅A)O(n \cdot A), pseudo-polynomial
RiverC(i,j)C(i, j): from dock ii to dock jjdirect trip, or first stop at kkO(n3)O(n^3)
LCSL(i,j)L(i, j): prefixes of both stringsmatch, or discard one characterO(∣a∣⋅∣b∣)O(\lvert a \rvert \cdot \lvert b \rvert)
Edit distanceD(i,j)D(i, j): prefixes of both stringsdelete, insert or substituteO(∣a∣⋅∣b∣)O(\lvert a \rvert \cdot \lvert b \rvert)

Practice​

  • 🔺 Pascal. Run combinationsDP and combinationsRecursive from the course repository for increasing nn with k=n/2k = n/2, and check the number of calls 2 C(n,k)−12\,C(n, k) - 1.
  • 🎒 Knapsack by hand. Fill the knapsack table for the data of the checkpoint (W=6W = 6), and recover the objects chosen by tracing back from V(4,6)V(4, 6). Which of the two optimal combinations do you obtain?
  • 💾 One row. Rewrite the knapsack algorithm using a single array of W+1W + 1 positions. In which direction must the inner loop run so that each object is used at most once?
  • 💰 The change with one array. Rewrite the change algorithm with a single array of A+1A + 1 positions. Why can the inner loop go from left to right here, while in the knapsack it had to go the other way?
  • 🚣 The route on the river. Extend the river algorithm to store the intermediate dock of each minimum, and write a method that prints the cheapest route between two docks.
  • 🔤 LCS. Implement the LCS algorithm, including the reconstruction of the subsequence, and test it with two versions of a short text.
Saved only in your browser
Was this lesson helpful?
Questions, or something wrong?

Errors, suggestions and public questions open a form on GitHub, visible to everyone.