1. Home
  2. Explore
  3. Computer Science
  4. Dynamic Programming

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Dynamic Programming

Speaker 1Speaker 2

Dynamic Programming

11:15
0:00-11:15
  1. Corey

    Welcome back. Today we’re starting a new section: algorithm design. So far, we’ve mostly learned powerful algorithms and data structures we can apply to problems. Now we’ll focus on how to build an algorithm from scratch, especially a polynomial-time algorithm, using a design paradigm called dynamic programming.

  2. Michael

    Dynamic programming is extremely general, and it’s one of the most powerful design approaches we’ll study. It builds on recursive algorithm design: describe a problem in terms of smaller problems, then reuse the solutions to those smaller problems instead of doing the same work again.

  3. Corey

    That recursive perspective fits naturally with proof by induction, which we’ve used throughout the class. It also gives us a useful way to organize dependencies between subproblems. We’ll use a framework called SRTBOT to keep the design steps straight.

  4. Michael

    SRTBOT stands for Subproblems, Relations, Topological order, Base cases, Original problem, and Time. The first step is to define the subproblems—the smaller questions we’ll solve along the way. Choosing the right subproblems is often the hardest part, and we generally want only polynomially many of them.

  5. Corey

    Next, write a relation that explains how to solve one subproblem using other subproblems. Then specify a topological order: an order in which all the dependencies are solved before the problem that needs them. The dependency graph should be acyclic, or recursive calls could keep circling forever.

  6. Michael

    After that, state the base cases, identify which subproblem—or combination of subproblems—gives the original answer, and analyze the running time. Those last steps sound straightforward, but the subproblems and the relation are usually where the design work happens.

  7. Corey

    Let’s apply the framework to an algorithm we already know: merge sort. For an array A, define a subproblem S(i,j) as sorting the items from index i up to, but not including, index j. The original problem is S(0,n), where n is the array length.

  8. Michael

    To solve S(i,j), split the range at a midpoint m. Recursively sort the two smaller ranges, from i to m and from m to j, and merge their sorted results. The base case is an empty range, which is already sorted.

  9. Corey

    A valid topological order is to solve ranges in increasing order of their length, j minus i. The two ranges on either side of the midpoint are strictly shorter, so their answers are ready first. This is SRTBOT applied to divide and conquer.

  10. Michael

    Now for a simple example that reveals why memoization matters: computing Fibonacci numbers. With f(1) and f(2) equal to one, each later number is f(i minus one) plus f(i minus two). The natural subproblems are to compute f(i) for each i from one through n.

  11. Corey

    The recurrence seems to give us a recursive algorithm right away: compute the two preceding Fibonacci numbers and add them. But if we implement that recursion without remembering results, the same subproblem gets recomputed many times.

  12. Michael

    Picture the recursion tree for f(n). Calls for f(n minus one) and f(n minus two) both eventually need f(n minus three). There are many overlaps like that, so the tree grows exponentially. The number of additions follows the Fibonacci recurrence too, and Fibonacci numbers grow exponentially.

  13. Corey

    Memoization fixes the repeated work with a simple idea: store each subproblem’s answer when you compute it. Keep a dictionary—or, for this example, a direct-access array—mapping each index i to f(i). Before solving a subproblem, check whether its answer is already stored; if it is, return it immediately.

  14. Michael

    If the answer isn’t stored, handle the base case or recursively compute the needed values, then save the result. For Fibonacci, once f(i minus one) has been computed, it has also led to f(i minus two), so that second recursive request can usually just look up the stored answer.

  15. Corey

    The important consequence is that each distinct subproblem is solved at most once. There are only n Fibonacci subproblems, and the non-recursive work for each is one addition. So in the usual model where those additions take constant time, the running time is order n.

  16. Michael

    There’s a subtle point about the size of the numbers. The nth Fibonacci number takes theta of n bits to write down, so an addition isn’t necessarily constant time if we account for individual bits. With a machine word of w bits, adding n-bit numbers takes about the ceiling of n over w time, giving a total of order n plus n squared over w for the additions.

  17. Corey

    Either way, memoization turns an exponential-time recursive algorithm into a polynomial-time one. The general analysis is to count the distinct subproblems and the non-recursive work for each. With memoization, we solve each subproblem once, so total time is bounded by the sum of that work over all subproblems.

  18. Michael

    That’s why both parts matter: having polynomially many subproblems isn’t enough if each one takes too long, and fast work per subproblem isn’t enough if there are exponentially many. If both counts are polynomial, the overall running time is polynomial.

  19. Corey

    Memoization doesn’t automatically improve every recursive algorithm. For merge sort, for example, the ranges in different recursive branches don’t repeat, so there’s no overlapping work to save. If we used memoization anyway and counted every possible range, there could be theta of n squared subproblems, and merging a range takes linear time in its length.

  20. Michael

    Summing that work gives an upper bound of order n cubed, which is polynomial but worse than merge sort’s actual order n log n running time. So the memoization analysis is a useful general bound, not always the best way to analyze an algorithm—and merge sort doesn’t need memoization.

  21. Corey

    A second example is shortest paths in a directed acyclic graph, or DAG. Given a source s, we want the shortest-path distance from s to every vertex. Define one subproblem for each vertex v: compute the distance from s to v.

  22. Michael

    For a vertex v, consider its incoming edges. Any path that arrives at v must come from some predecessor u, so the distance to v is the minimum, over incoming edges u-to-v, of the distance to u plus the edge’s weight. If no path reaches v, the distance is infinity. The base case is that the distance from s to itself is zero.

  23. Corey

    The graph’s topological order gives us an order for these subproblems, because each predecessor comes before the vertex it points to. The original task is simply to solve the subproblem for every vertex. The non-recursive work for v is proportional to the number of its incoming edges, so summing over vertices gives order V plus E time.

  24. Michael

    This is essentially the DAG shortest-path algorithm we’ve seen before, just viewed from the other direction. Relaxing incoming edges one at a time is another way to compute the minimum in that recurrence. And the recursive, memoized version implicitly explores the subproblem graph with depth-first search, while the DAG’s acyclic structure ensures the dependencies can be completed.

  25. Corey

    Now let’s design a dynamic program for a new problem: a bowling game with pins arranged in a line. Pin i has value v(i). You may leave a pin standing, knock down one pin for its value, or knock down two adjacent pins together for the product of their values. The goal is to maximize your total score.

  26. Michael

    The values can be positive or negative, so local intuition can be misleading. Pairing two negative pins can give a positive product, while hitting a single negative pin may hurt your score. And you don’t have to knock down every pin.

  27. Corey

    For sequence problems, useful subproblem choices often include prefixes, suffixes, or substrings. A sequence of length n has order n prefixes and suffixes, and order n squared substrings. Substrings must be consecutive; subsequences can skip positions, and there can be exponentially many of those, so they’re often a poor choice when we want only polynomially many subproblems.

  28. Michael

    For bowling, suffixes are enough. Let B(i) be the maximum score possible using the suffix of pins starting at i and continuing to the end. This definition says exactly what the subproblem is trying to achieve. The original answer is B(0), since that suffix contains every pin.

  29. Corey

    To write the recurrence, focus on the first pin in the suffix, pin i. One option is to skip it, leaving B(i plus one). A second option is to hit it alone, earning v(i) and then solving the remaining suffix, for a total of v(i) plus B(i plus one).

  30. Michael

    The third option is to hit pin i together with pin i plus one. That earns their product, v(i) times v(i plus one), and leaves the suffix starting at i plus two. So, when there are at least two pins left, B(i) is the maximum of those three options.

  31. Corey

    At the end of the sequence there are no pins, so B(n) equals zero. The paired option is available only when i is less than n minus one. Because every recurrence step moves to a later suffix, a valid topological order is decreasing i: solve from right to left.

  32. Michael

    There are only order n suffixes, and each recurrence does constant non-recursive work: a few additions, a product, and a maximum. With memoization, that gives order n time. We’ve turned a problem with many possible ways to play into a small set of reusable subproblems.

  33. Corey

    You can also write this as bottom-up dynamic programming instead of recursive code. Set B(n) to zero, then use a loop from n minus one down to zero, filling in each B(i) from the values already computed to its right. Finally, return B(0).

  34. Michael

    Bottom-up dynamic programming makes the topological order explicit and avoids recursive calls. Once you have the subproblems, relation, order, base case, and original answer, you can often translate them directly into a loop like that.

  35. Corey

    The bowling recurrence also illustrates local brute force. At each position, try every possible action on the first pin—skip it, hit it alone, or pair it with the next pin—and take the best result. Trying choices at every position could sound exponential, but memoization prevents us from repeatedly solving the same suffix.

  36. Michael

    The broader design intuition is to identify a feature of a solution that lets you reduce the problem to smaller subproblems. With suffixes, focus on the first item or first few items; with prefixes, focus on the last item. For a substring, sometimes a useful choice is an item in the middle, whose removal can leave two smaller substrings.

  37. Corey

    For an optimization problem, the recurrence often takes a maximum or minimum over the choices. Other problems may combine choices in a different way. The key is to make sure each option leads to subproblems in your chosen, polynomial-sized family.

  38. Michael

    That’s the central promise of dynamic programming: carefully chosen subproblems let us explore many possible decisions without repeating work. SRTBOT gives us a checklist for building the algorithm, and memoization—or a bottom-up table—turns that recursive structure into an efficient computation.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent