Exercises: Dynamic Programming
These exercises review the two lessons on dynamic programming. For each problem, follow the design steps of the first lesson: define the subproblems, write the recurrence with its base cases, decide the order in which to fill the table, and, when needed, recover the solution from the table. Try each one before reading its solution: the solutions are grouped at the end of the page.
Counting
6.1. Stairs. A child climbs a staircase of steps, taking 1, 2 or 3 steps at a time. In how many different ways can the child reach the top? Give the recurrence and compute the answer for .
6.2. Paths in a grid. A robot starts at the top-left cell of a grid with 4 rows and 5 columns and must reach the bottom-right cell, moving only right or down. How many different paths are there? And if the cells in row 1, column 2 and in row 2, column 1 (counting rows and columns from 0) are blocked?
Optimization
6.3. Longest increasing subsequence. Find the length of the longest strictly increasing subsequence (not necessarily contiguous) of 10 9 2 5 3 7 101 18, and one such subsequence. Give an algorithm.
6.4. Cutting a rod. A rod of length 8 can be cut into pieces of integer length and sold. A piece of length sells for :
| Length | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|---|---|---|---|---|---|---|---|---|
| Price | 1 | 5 | 8 | 9 | 10 | 17 | 17 | 20 |
What is the maximum income, and how should the rod be cut?
6.5. Multiplying a chain of matrices. Matrix multiplication is associative, but the cost depends on the order: multiplying a matrix by a matrix takes scalar multiplications.
- (a) For (), () and (), compare with .
- (b) Design a dynamic programming algorithm for a chain of matrices, and apply it to dimensions , , and .
6.6. Non-adjacent sum. Choose elements of 6 7 1 30 8 2 4 with the maximum sum, without choosing two adjacent elements. Solve it in time and extra memory.
6.7. Palindromes. What is the minimum number of characters that must be inserted (anywhere) into ABRACADABRA to turn it into a palindrome? Hint: relate it to the longest subsequence that is itself a palindrome, and to the longest common subsequence.
Understanding the technique
6.8. Does the principle of optimality hold? For each problem, say whether an optimal solution is made of optimal solutions to its subproblems:
- (a) the shortest path between two nodes of a graph with positive weights;
- (b) the longest simple path (without repeated nodes) between two nodes;
- (c) the cheapest path between two nodes that uses at most edges.
6.9. Memoization. The recursive computation of by Pascal's rule makes calls. How many distinct subproblems does it have? How many times is the body of the method executed if the results are memoized?
6.10. Saving memory. The table of the LCS of two strings of lengths and has cells. Show how to compute the length of the LCS with only memory. What do you lose?
Solutions
6.1. Let be the number of ways. The last move is 1, 2 or 3 steps, so
( counts the empty climb). Filling a vector from 3 to : 4, 7, 13, 24, 44, 81, 149, 274 for . time, and only the last three values need to be stored. The naive recursion would make a number of calls that grows like .
6.2. Without obstacles, each path is a sequence of 3 moves down and 4 moves right, in any order: paths. With obstacles, let be the number of paths from the start to cell : , with on blocked cells and . Filling row by row:
1 1 1 1 1
1 2 X 1 2
1 X 0 1 3
1 1 1 2 5
5 paths. The table is filled in .
6.3. Let be the length of the longest increasing subsequence that ends at position : , or 1 if there is no such . For the array: . The answer is the maximum, 4: for example 2 3 7 18 (or 2 5 7 101). Storing, for each , the that gave the maximum allows recovering the subsequence backwards. time. (There is an algorithm that keeps, for each length, the smallest possible last element and uses binary search.)
6.4. Let be the best income for a rod of length : , with . The first piece has length and the rest is cut optimally. Filling the vector: for lengths 1 to 8. The maximum income is 22, cutting the rod into pieces of 2 and 6 (). .
6.5.
- (a) : . : , six times more.
- (b) With dimensions (matrix is ), let be the minimum cost of . The last multiplication splits the chain at some :
The table is filled by increasing chain length (diagonals). For :
| 0 | 24,000 | 14,000 | 26,000 | |
| 0 | 6,000 | 12,000 | ||
| 0 | 9,000 | |||
| 0 |
The minimum is 26,000, with the order . Storing the best of each cell allows recovering the parenthesization. time, memory.
6.6. Keep two values while scanning: the best sum that includes the current element and the best that excludes it. For each element : the new "include" is the old "exclude" plus , and the new "exclude" is the maximum of the old two.
int include = 0, exclude = 0;
for (int x : a) {
int newInclude = exclude + x;
exclude = Math.max(include, exclude);
include = newInclude;
}
return Math.max(include, exclude);
The answer is 41, choosing . Note that greedily taking the largest element first (30) and then the largest allowed ones also gives 41 here, but fails in general: in 5 6 5 it takes 6, while the optimum is .
6.7. The characters that do not need a partner are those of the longest palindromic subsequence (LPS); every other character needs one inserted copy. So the answer is . The LPS of a string is the LCS of the string and its reverse. For ABRACADABRA (), the LPS has length 7 (for example ABACABA), so 4 insertions are needed. with the LCS table. (For ALGORITHM, with no repeated letters, the LPS has length 1, and 8 insertions are needed.)
6.8.
- (a) Yes. If the shortest path from to passes through , its part from to must be a shortest path from to ; otherwise, replacing it by a shorter one would shorten the whole path. This is what Floyd's and Dijkstra's algorithms exploit.
- (b) No. The longest simple path from to through need not be made of longest simple paths from to and from to : those two paths may share nodes, and joining them would not be a simple path. The dynamic programming lesson discusses this example.
- (c) Yes, if the subproblems include the number of edges allowed: the best path from to with at most edges is made of a best path from to some with at most edges plus the edge from to . Adding the right parameter to the subproblem is often what makes the principle hold.
6.9. The subproblems are the values reached from : those with and , which are at most . With memoization, the body of the method executed exactly 255 times in our run, once per distinct subproblem reached; every other call returns a stored value immediately. Over a million times fewer than the 310 million calls of the plain recursion.
6.10. Each row of the LCS table depends only on the previous row. Keeping two arrays of length (putting the shorter string along the columns), and swapping them after each row, computes the length with memory and the same time. What is lost is the ability to recover the subsequence by walking back through the table, because the earlier rows have been overwritten. (Hirschberg's algorithm recovers it in linear space by combining this idea with divide and conquer.)
Errors, suggestions and public questions open a form on GitHub, visible to everyone.