# Dynamic Programming

### Elementary Recurrences

10.1. Up to ${\displaystyle k}$ steps in a single bound! A child is running up a staircase with ${\displaystyle n}$ steps and can hop between 1 and ${\displaystyle k}$ steps at a time. Design an algorithm to count how many possible ways the child can run up the stairs, as a function of ${\displaystyle n}$ and ${\displaystyle k}$. What is the running time of your algorithm?

10.2. Imagine you are a professional thief who plans to rob houses along a street of ${\displaystyle n}$ homes. You know the loot at house ${\displaystyle i}$ is worth ${\displaystyle m_{i}}$, for ${\displaystyle 1\leq i\leq n}$, but you cannot rob neighboring houses because their connected security systems will automatically contact the police if two adjacent houses are broken into. Give an efficient algorithm to determine the maximum amount of money you can steal without alerting the police.

10.3. Basketball games are a sequence of 2-point shots, 3-point shots, and 1-point free throws. Give an algorithm that computes how many possible mixes (1s,2s,3s) of scoring add up to a given ${\displaystyle n}$. For ${\displaystyle n}$ = 5 there are four possible solutions: (5, 0, 0), (2, 0, 1), (1, 2, 0), and (0, 1, 1).

10.4. Basketball games are a sequence of 2-point shots, 3-point shots, and 1-point free throws. Give an algorithm that computes how many possible scoring sequences add up to a given ${\displaystyle n}$. For ${\displaystyle n}$ = 5 there are thirteen possible sequences, including 1-2-1-1, 3-2, and 1-1-1-1-1.

10.5. Given an ${\displaystyle s*t}$ grid filled with non-negative numbers, find a path from top left to bottom right that minimizes the sum of all numbers along its path. You can only move either down or right at any point in time.
(a) Give a solution based on Dijkstra’s algorithm. What is its time complexity as a function of ${\displaystyle s}$ and ${\displaystyle t}$?
(b) Give a solution based on dynamic programming. What is its time complexity as a function of ${\displaystyle s}$ and ${\displaystyle t}$?

### Edit Distance

10.6. Typists often make transposition errors exchanging neighboring characters, such as typing “setve” for “steve.” This requires two substitutions to fix under the conventional definition of edit distance.
Incorporate a swap operation into our edit distance function, so that such neighboring transposition errors can be fixed at the cost of one operation.

10.7. Suppose you are given three strings of characters: ${\displaystyle X}$, ${\displaystyle Y}$, and ${\displaystyle Z}$, where ${\displaystyle |X|=n}$, ${\displaystyle |Y|=m}$, and ${\displaystyle |Z|=n+m}$. ${\displaystyle Z}$ is said to be a shuffle of ${\displaystyle X}$ and ${\displaystyle Y}$ iff ${\displaystyle Z}$ can be formed by interleaving the characters from ${\displaystyle X}$ and ${\displaystyle Y}$ in a way that maintains the left-to-right ordering of the characters from each string.
(a) Show that cchocohilaptes is a shuffle of chocolate and chips, but chocochilatspe is not.
(b) Give an efficient dynamic programming algorithm that determines whether ${\displaystyle Z}$ is a shuffle of ${\displaystyle X}$ and ${\displaystyle Y}$. (Hint: the values of the dynamic programming matrix you construct should be Boolean, not numeric.)

10.8. The longest common substring (not subsequence) of two strings ${\displaystyle X}$ and ${\displaystyle Y}$ is the longest string that appears as a run of consecutive letters in both strings. For example, the longest common substring of photograph and tomography is ograph.
(a) Let ${\displaystyle n=|X|}$ and ${\displaystyle m=|Y|}$. Give a ${\displaystyle \Theta (nm)}$ dynamic programming algorithm for longest common substring based on the longest common subsequence/edit distance algorithm.
(b) Give a simpler ${\displaystyle \Theta (nm)}$ algorithm that does not rely on dynamic programming.

10.9. The longest common subsequence (LCS) of two sequences ${\displaystyle T}$ and ${\displaystyle P}$ is the longest sequence ${\displaystyle L}$ such that ${\displaystyle L}$ is a subsequence of both ${\displaystyle T}$ and ${\displaystyle P}$. The shortest common supersequence (SCS) of ${\displaystyle T}$ and ${\displaystyle P}$ is the smallest sequence ${\displaystyle L}$ such that both ${\displaystyle T}$ and ${\displaystyle P}$ are a subsequence of ${\displaystyle L}$.
(a) Give efficient algorithms to find the LCS and SCS of two given sequences.
(b) Let ${\displaystyle d(T,P)}$ be the minimum edit distance between ${\displaystyle T}$ and ${\displaystyle P}$ when no substitutions are allowed (i.e., the only changes are character insertion and deletion). Prove that ${\displaystyle d(T,P)=|SCS(T,P)|-|LCS(T,P)|}$ where ${\displaystyle |SCS(T,P)|(|LCS(T,P)|)}$ is the size of the shortest SCS (longest LCS) of ${\displaystyle T}$ and ${\displaystyle P}$.

10.10. Suppose you are given ${\displaystyle n}$ poker chips stacked in two stacks, where the edges of all chips can be seen. Each chip is one of three colors. A turn consists of choosing a color and removing all chips of that color from the tops of the stacks. The goal is to minimize the number of turns until the chips are gone.
For example, consider the stacks ${\displaystyle (RRGG,GBBB)}$. Playing red, green, and then blue suffices to clear the stacks in three moves. Give an ${\displaystyle O(n^{2})}$ dynamic programming algorithm to find the best strategy for a given pair of chip piles.

### Greedy Algorithms

10.11. Let ${\displaystyle P_{1},P_{2},...,P_{n}}$ be ${\displaystyle n}$ programs to be stored on a disk with capacity ${\displaystyle D}$ megabytes. Program ${\displaystyle P_{i}}$ requires ${\displaystyle s_{i}}$ megabytes of storage. We cannot store them all because ${\displaystyle D<\sum _{i=1}^{n}s_{i}}$
(a) Does a greedy algorithm that selects programs in order of non-decreasing ${\displaystyle s_{i}}$ maximize the number of programs held on the disk? Prove or give a counter-example.
(b) Does a greedy algorithm that selects programs in order of non-increasing ${\displaystyle s_{i}}$ use as much of the capacity of the disk as possible? Prove or give a counter-example.

10.12. Coins in the United States are minted with denominations of 1, 5, 10, 25, and 50 cents. Now consider a country whose coins are minted with denominations of ${\displaystyle {d_{1},...,d_{k}}}$ units. We seek an algorithm to make change of ${\displaystyle n}$ units using the minimum number of this country’s coins.
(a) The greedy algorithm repeatedly selects the biggest coin no bigger than the amount to be changed and repeats until it is zero. Show that the greedy algorithm does not always use the minimum number of coins in a country whose denominations are {1, 6, 10}.
(b) Give an efficient algorithm that correctly determines the minimum number of coins needed to make change of ${\displaystyle n}$ units using denominations ${\displaystyle {d_{1},...,d_{k}}}$. Analyze its running time.

10.13. Coins in the United States are minted with denominations of 1, 5, 10, 25, and 50 cents. Now consider a country whose coins are minted with denominations of ${\displaystyle {d_{1},...,d_{k}}}$ units. We want to count how many distinct ways ${\displaystyle C(n)}$ there are to make change of ${\displaystyle n}$ units. For example, in a country whose denominations are {1, 6, 10}, ${\displaystyle C(5)=1}$, ${\displaystyle C(6)}$ to ${\displaystyle C(9)=2}$, ${\displaystyle C(10)=3}$, and ${\displaystyle C(12)=4}$.
(a) How many ways are there to make change of 20 units from {1, 6, 10}?
(b) Give an efficient algorithm to compute ${\displaystyle C(n)}$, and analyze its complexity. (Hint: think in terms of computing ${\displaystyle C(n,d)}$, the number of ways to make change of ${\displaystyle n}$ units with highest denomination ${\displaystyle d}$. Be careful to avoid overcounting.)

10.14. In the single-processor scheduling problem, we are given a set of ${\displaystyle n}$ jobs ${\displaystyle J}$. Each job ${\displaystyle i}$ has a processing time ${\displaystyle t_{i}}$, and a deadline ${\displaystyle d_{i}}$. A feasible schedule is a permutation of the jobs such that when the jobs are performed in that order, every job is finished before its deadline. The greedy algorithm for single-processor scheduling selects the job with the earliest deadline first.
Show that if a feasible schedule exists, then the schedule produced by this greedy algorithm is feasible.

### Number Problems

10.15. You are given a rod of length ${\displaystyle n}$ inches and a table of prices obtainable for rod-pieces of size ${\displaystyle n}$ or smaller. Give an efficient algorithm to find the maximum value obtainable by cutting up the rod and selling the pieces. For example, if ${\displaystyle n=8}$ and the values of different pieces are:
${\displaystyle {\begin{array}{|c|c|c|c|c|c|c|c||c|}length&1&2&3&4&5&6&7&8\\\hline price&1&5&8&9&10&17&17&20\\\end{array}}}$
then the maximum obtainable value is 22, by cutting into pieces of lengths 2 and 6.

10.16. Your boss has written an arithmetic expression of n terms to compute your annual bonus, but permits you to parenthesize it however you wish. Give an efficient algorithm to design the parenthesization to maximize the value. For the expression:
${\displaystyle 6+2*0-4}$
there exist parenthesizations with values ranging from −32 to 2.

10.17. Given a positive integer ${\displaystyle n}$, find an efficient algorithm to compute the smallest number of perfect squares (e.g. 1, 4, 9, 16, . . .) that sum to ${\displaystyle n}$. What is the running time of your algorithm?

10.18. Given an array ${\displaystyle A}$ of ${\displaystyle n}$ integers, find an efficient algorithm to compute the largest sum of a continuous run. For ${\displaystyle A=[-3,2,7,-3,4,-2,0,1]}$, the largest such sum is 10, from the second through fifth positions.

10.19. Two drivers have to divide up ${\displaystyle m}$ suitcases between them, where the weight of the ${\displaystyle ith}$ suitcase is ${\displaystyle w_{i}}$. Give an efficient algorithm to divide up the loads so the two drivers carry equal weight, if possible.

10.20. The knapsack problem is as follows: given a set of integers ${\displaystyle S={s_{1},s_{2},...,s_{n}}}$, and a given target number ${\displaystyle T}$, find a subset of ${\displaystyle S}$ that adds up exactly to ${\displaystyle T}$. For example, within ${\displaystyle S={1,2,5,9,10}}$ there is a subset that adds up to ${\displaystyle T=22}$ but not ${\displaystyle T=23}$.
Give a dynamic programming algorithm for knapsack that runs in ${\displaystyle O(nT)}$ time.

10.21. The integer partition takes a set of positive integers ${\displaystyle S={s_{1},...,s_{n}}}$ and seeks a subset ${\displaystyle I\subset S}$ such that
${\displaystyle \sum _{i\in I}s_{i}=\sum _{i\notin I}s_{i}}$
Let ${\displaystyle \sum _{i\in S}s_{i}=M}$. Give an ${\displaystyle O(nM)}$ dynamic programming algorithm to solve the integer partition problem.

10.22. Assume that there are n numbers (some possibly negative) on a circle, and we wish to find the maximum contiguous sum along an arc of the circle. Give an efficient algorithm for solving this problem.

10.23. A certain string processing language allows the programmer to break a string into two pieces. It costs ${\displaystyle n}$ units of time to break a string of ${\displaystyle n}$ characters into two pieces, since this involves copying the old string. A programmer wants to break a string into many pieces, and the order in which the breaks are made can affect the total amount of time used. For example, suppose we wish to break a 20-character string after characters 3, 8, and 10. If the breaks are made in left-to-right order, then the first break costs 20 units of time, the second break costs 17 units of time, and the third break costs 12 units of time, for a total of 49 units. If the breaks are made in right-to-left order, the first break costs 20 units of time, the second break costs 10 units of time, and the third break costs 8 units of time, for a total of only 38 units.
Give a dynamic programming algorithm that takes a list of character positions after which to break and determines the cheapest break cost in ${\displaystyle O(n^{3})}$ time.

10.24. Consider the following data compression technique. We have a table of ${\displaystyle m}$ text strings, each at most ${\displaystyle k}$ in length. We want to encode a data string ${\displaystyle D}$ of length ${\displaystyle n}$ using as few text strings as possible. For example, if our table contains ${\displaystyle (a,ba,abab,b)}$ and the data string is ${\displaystyle bababbaababa}$, the best way to encode it is ${\displaystyle (b,abab,ba,abab,a)-a}$ total of five code words. Give an ${\displaystyle O(nmk)}$ algorithm to find the length of the best encoding. You may assume that every string has at least one encoding in terms of the table.

10.25. The traditional world chess championship is a match of 24 games. The current champion retains the title in case the match is a tie. Each game ends in a win, loss, or draw (tie) where wins count as 1, losses as 0, and draws as ${\displaystyle 1/2}$. The players take turns playing white and black. White plays first and so has an advantage. The champion plays white in the first game. The champ has probabilities ${\displaystyle w_{w}}$, ${\displaystyle w_{d}}$, and ${\displaystyle w_{l}}$ of winning, drawing, and losing playing white, and has probabilities ${\displaystyle b_{w}}$, ${\displaystyle b_{d}}$, and ${\displaystyle b_{l}}$ of winning, drawing, and losing playing black.
(a) Write a recurrence for the probability that the champion retains the title. Assume that there are ${\displaystyle g}$ games left to play in the match and that the champion needs to get ${\displaystyle i}$ points (which may be a multiple of ${\displaystyle 1/2}$).
(b) Based on your recurrence, give a dynamic programming algorithm to calculate the champion’s probability of retaining the title.
(c) Analyze its running time for an ${\displaystyle n}$ game match.

10.26. Eggs break when dropped from great enough height. Specifically, there must be a floor ${\displaystyle f}$ in any sufficiently tall building such that an egg dropped from the ${\displaystyle f}$th floor breaks, but one dropped from the ${\displaystyle (f-1)}$st floor will not. If the egg always breaks, then ${\displaystyle f=1}$. If the egg never breaks, then ${\displaystyle f=n+1}$.
You seek to find the critical floor ${\displaystyle f}$ using an ${\displaystyle n-floor}$ building. The only operation you can perform is to drop an egg off some floor and see what happens. You start out with ${\displaystyle k}$ eggs, and seek to make as few drops as possible. Broken eggs cannot be reused. Let ${\displaystyle E(k,n)}$ be the minimum number of egg drops that will always suffice.
(a) Show that ${\displaystyle E(1,n)=n}$.
(b) Show that ${\displaystyle E(k,n)=\Theta (n^{1/k})}$.
(c) Find a recurrence for ${\displaystyle E(k,n)}$. What is the running time of the dynamic program to find ${\displaystyle E(k,n)}$?

### Graphing Problem

10.27. Consider a city whose streets are defined by an ${\displaystyle X*Y}$ grid. We are interested in walking from the upper left-hand corner of the grid to the lower right-hand corner.
Unfortunately, the city has bad neighborhoods, whose intersections we do not want to walk in. We are given an ${\displaystyle X*Y}$ matrix bad, where ${\displaystyle bad[i,j]=}$ “yes” iff the intersection between streets ${\displaystyle i}$ and ${\displaystyle j}$ is in a neighborhood to avoid.
(a) Give an example of the contents of bad such that there is no path across the grid avoiding bad neighborhoods.
(b) Give an ${\displaystyle O(XY)}$ algorithm to find a path across the grid that avoids bad neighborhoods.
(c) Give an ${\displaystyle O(XY)}$ algorithm to find the shortest path across the grid that avoids bad neighborhoods. You may assume that all blocks are of equal length. For partial credit, give an ${\displaystyle O(X^{2}Y^{2})}$ algorithm.

10.28. Consider the same situation as the previous problem. We have a city whose streets are defined by an ${\displaystyle X*Y}$ grid. We are interested in walking from the upper left-hand corner of the grid to the lower right-hand corner. We are given an ${\displaystyle X*Y}$ matrix bad, where ${\displaystyle bad[i,j]=}$ “yes” iff the intersection between streets ${\displaystyle i}$ and ${\displaystyle j}$ is somewhere we want to avoid.
If there were no bad neighborhoods to contend with, the shortest path across the grid would have length ${\displaystyle (X-1)+(Y-1)}$ blocks, and indeed there would be many such paths across the grid. Each path would consist of only rightward and downward moves.
Give an algorithm that takes the array bad and returns the number of safe paths of length ${\displaystyle X+Y-2}$. For full credit, your algorithm must run in ${\displaystyle O(XY)}$.

10.29. You seek to create a stack out of ${\displaystyle n}$ boxes, where box ${\displaystyle i}$ has width ${\displaystyle w_{i}}$, height ${\displaystyle h_{i}}$, and depth ${\displaystyle d_{i}}$. The boxes cannot be rotated, and can only be stacked on top of one another when each box in the stack is strictly larger than the box above it in width, height, and depth. Give an efficient algorithm to construct the tallest possible stack, where the height is the sum of the heights of each box in the stack.

### Design Problems

10.30. Consider the problem of storing ${\displaystyle n}$ books on shelves in a library. The order of the books is fixed by the cataloging system and so cannot be rearranged. Therefore, we can speak of a book ${\displaystyle b_{i}}$, where ${\displaystyle 1\leq i\leq n}$, that has a thickness ${\displaystyle t_{i}}$ and height ${\displaystyle h_{i}}$. The length of each bookshelf at this library is ${\displaystyle L}$.
Suppose all the books have the same height ${\displaystyle h}$ (i.e., ${\displaystyle h=h_{i}}$ for all ${\displaystyle i}$) and the shelves are all separated by a distance greater than ${\displaystyle h}$, so any book fits on any shelf. The greedy algorithm would fill the first shelf with as many books as we can until we get the smallest ${\displaystyle i}$ such that ${\displaystyle b_{i}}$ does not fit, and then repeat with subsequent shelves. Show that the greedy algorithm always finds the book placement that uses the minimum number of shelves, and analyze its time complexity.

10.31. This is a generalization of the previous problem. Now consider the case where the height of the books is not constant, but we have the freedom to adjust the height of each shelf to that of the tallest book on the shelf. Here the cost of a particular layout is the sum of the heights of the largest book on each shelf.
1. Give an example to show that the greedy algorithm of stuffing each shelf as full as possible does not always give the minimum overall height.
2. Give an algorithm for this problem, and analyze its time complexity. (Hint: use dynamic programming.)

10.32. Consider a linear keyboard of lowercase letters and numbers, where the left-most 26 keys are the letters A–Z in order, followed by the digits 0–9 in order, followed by the 30 punctuation characters in a prescribed order, and ended on a blank. Assume you start with your left index finger on the “A” and your right index finger on the blank.
Give a dynamic programming algorithm that finds the most efficient way to type a given text of length ${\displaystyle n}$, in terms of minimizing total movement of the fingers involved. For the text ${\displaystyle ABABABAB...ABAB}$, this would involve shifting both fingers all the way to the left side of the keyboard. Analyze the complexity of your algorithm as a function of ${\displaystyle n}$ and ${\displaystyle k}$, the number of keys on the keyboard.

10.33. You have come back from the future with an array ${\displaystyle G}$, where ${\displaystyle G[i]}$ tells you the price of Google stock ${\displaystyle i}$ days from now, for ${\displaystyle 1\leq i\leq n}$. You seek to use this information to maximize your profit, but are only permitted to complete at most one transaction (i.e. either buy one or sell one share of the stock) per day. Design an efficient algorithm to construct the buy–sell sequence to maximize your profit. Note that you cannot sell a share unless you currently own one.

10.34. You are given a string of ${\displaystyle n}$ characters ${\displaystyle S=s_{1}...s_{n}}$, which you believe to be a compressed text document in which all spaces have been removed, like itwasthebestoftimes.
(a) You seek to reconstruct the document using a dictionary, which is available in the form of a Boolean function ${\displaystyle dict(w)}$, where ${\displaystyle dict(w)}$ is true iff string ${\displaystyle w}$ is a valid word in the language. Give an ${\displaystyle O(n^{2})}$ algorithm to determine whether string ${\displaystyle S}$ can be reconstituted as a sequence of valid words, assuming calls to ${\displaystyle dict(w}$ take unit time.
(b) Now assume you are given the dictionary as a set of ${\displaystyle m}$ words each of length at most l. Give an efficient algorithm to determine whether string ${\displaystyle S}$ can be reconstituted as a sequence of valid words, and its running time.

10.35. Consider the following two-player game, where you seek to get the biggest score. You start with an n-digit integer ${\displaystyle N}$. With each move, you get to take either the first digit or the last digit from what is left of ${\displaystyle N}$, and add that to your score, with your opponent then doing the same thing to the now smaller number. You continue taking turns removing digits until none are left. Give an efficient algorithm that finds the best possible score that the first player can get for a given digit string ${\displaystyle N}$, assuming the second player is as smart as can be.

10.36. Given an array of ${\displaystyle n}$ real numbers, consider the problem of finding the maximum sum in any contiguous subarray of the input. For example, in the array
${\displaystyle [31,-41,59,26,-53,58,97,-93,-23,84]}$
the maximum is achieved by summing the third through seventh elements, where 59 + 26 + (−53) + 58 + 97 = 187. When all numbers are positive, the entire array is the answer, while when all numbers are negative, the empty array maximizes the total at 0.
1. Give a simple and clear ${\displaystyle \Theta (n^{2})}$-time algorithm to find the maximum contiguous subarray.
2. Now give a ${\displaystyle \Theta (n)}$-time dynamic programming algorithm for this problem. To get partial credit, you may instead give a correct ${\displaystyle O(nlogn)}$ divide-and-conquer algorithm.

10.37. Consider the problem of examining a string ${\displaystyle x=x_{1}x_{2}\ldots x_{n}}$ from an alphabet of ${\displaystyle k}$ symbols, and a multiplication table over this alphabet. Decide whether or not it is possible to parenthesize ${\displaystyle x}$ in such a way that the value of the resulting expression is ${\displaystyle a}$, where ${\displaystyle a}$ belongs to the alphabet. The multiplication table is neither commutative or associative, so the order of multiplication matters.

${\displaystyle {\begin{array}{c|ccc}&a&b&c\\\hline a&a&c&c\\b&a&a&b\\c&c&c&c\\\end{array}}}$

For example, consider the above multiplication table and the string ${\displaystyle bbbba}$. Parenthesizing it ${\displaystyle (b(bb))(ba)}$ gives ${\displaystyle a}$, but ${\displaystyle ((((bb)b)b)a)}$ gives ${\displaystyle c}$.
Give an algorithm, with time polynomial in ${\displaystyle n}$ and ${\displaystyle k}$, to decide whether such a parenthesization exists for a given string, multiplication table, and goal element.

10.38. Let α and β be constants. Assume that it costs α to go left in a binary search tree, and β to go right. Devise an algorithm that builds a tree with optimal expected query cost, given keys ${\displaystyle k_{1},...,k_{n}}$ and the probabilities that each will be searched ${\displaystyle p_{1},...,p_{n}}$.

### Interview Problems

10.39. Given a set of coin denominations, find the minimum number of coins to make a certain amount of change.

10.40. You are given an array of n numbers, each of which may be positive, negative, or zero. Give an efficient algorithm to identify the index positions ${\displaystyle i}$ and ${\displaystyle j}$ to obtain the maximum sum of the ${\displaystyle i}$th through ${\displaystyle j}$th numbers.

10.41. Observe that when you cut a character out of a magazine, the character on the reverse side of the page is also removed. Give an algorithm to determine whether you can generate a given string by pasting cutouts from a given magazine. Assume that you are given a function that will identify the character and its position on the reverse side of the page for any given character position.

Back to Chapter List