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

Designing Algorithms with Recursion and Dynamic Programming

A powerful algorithm does more than follow a fixed recipe for one input. It uses a small set of instructions to solve problems of many different sizes. Recursion is one way to organize those instructions: a problem is solved by expressing it in terms of smaller problems. Dynamic programming builds on this idea by remembering solutions to smaller problems and reusing them instead of computing them repeatedly.

This lesson develops a systematic approach to recursive algorithm design, then uses it to understand dynamic programming through Fibonacci numbers, shortest paths in directed acyclic graphs, and a bowling optimization problem.

A framework for recursive algorithm design: SRTBOT

A useful checklist for designing a recursive algorithm is SRTBOT:

  • Subproblems: What smaller problems should be solved?
  • Relations: How can a subproblem’s solution be built from other subproblem solutions?
  • Topological order: In what order can the subproblems be solved so that every dependency is ready in time?
  • Base cases: Which smallest problems can be solved directly?
  • Original problem: Which subproblem, or combination of subproblems, gives the answer to the original task?
  • Time: How much work does the algorithm require?

The hardest design choices are often the first two: defining useful subproblems and finding a relation between them. A subproblem must be small or simple enough to help, but the collection of subproblems must also be limited enough to compute efficiently.

Subproblems and their dependency graph

A recursive algorithm defines some problems in terms of other problems. These relationships can be represented by a subproblem graph:

  • Each vertex represents a subproblem.
  • An edge represents a dependency: one subproblem needs the answer to another.

For the recursion to finish, dependencies must not form a cycle. If solving one subproblem leads back to solving that same subproblem again, the algorithm could recurse forever. A topological order is an ordering of the subproblems in which every dependency is handled before the subproblem that needs it. A topological order therefore gives a safe order for solving the problems.

Sometimes that order is stated explicitly, such as “solve problems in increasing order of size.” In other cases, the structure of a directed acyclic graph already supplies the order.

Example: merge sort in the SRTBOT framework

Merge sort illustrates the framework, even though it does not gain much from dynamic programming.

Suppose the input array is AAA, with length nnn. Define a subproblem s(i,j)s(i,j)s(i,j) to mean: return the elements of AAA from index iii up to, but not including, index jjj, in sorted order. The original task is s(0,n)s(0,n)s(0,n).

To solve s(i,j)s(i,j)s(i,j), split the interval at a middle index mmm. Recursively sort the two halves, then merge the sorted results:

s(i,j)=merge⁡(s(i,m),s(m,j)).s(i,j)=\operatorname{merge}\bigl(s(i,m),s(m,j)\bigr).s(i,j)=merge(s(i,m),s(m,j)).

The merge operation combines two already sorted arrays into one sorted array. Because mmm lies between iii and jjj, both recursive subproblems are smaller than the original one. A valid topological order is therefore increasing interval length, j−ij-ij−i.

The base cases are intervals with at most one element, which are already sorted. The original problem is s(0,n)s(0,n)s(0,n). Merge sort’s familiar running time is Θ(nlog⁡n)\Theta(n\log n)Θ(nlogn).

This example shows how a recursive algorithm can fit SRTBOT. It also prepares for a key distinction: recursion alone does not necessarily make an algorithm dynamic programming. The important additional opportunity is reusing work when the same subproblem appears more than once.

A recursive algorithm organizes a problem through smaller problems. Dynamic programming adds a systematic way to store and reuse their solutions.

Think About It: Why does a topological order help prevent recursive calls from getting stuck in a cycle?

Memoization: remembering solutions

Memoization means storing a subproblem’s solution when it is first computed and looking it up if that subproblem is needed again. The storage can be a dictionary, a table, or—when subproblems have simple numeric indices—a direct-access array. The stored collection is often called a memo.

A memoized recursive function follows this pattern:

  1. Check whether the requested subproblem is already in the memo. If so, return its stored solution.
  2. If it is a base case, solve it directly.
  3. Otherwise, recursively solve the needed smaller problems and combine their answers.
  4. Store the result in the memo and return it.

The key consequence is that each distinct subproblem is solved at most once. Without memoization, different recursive branches may repeatedly do the same work.

Fibonacci numbers: a simple example of repeated work

The Fibonacci numbers are defined by

F1=F2=1,Fi=Fi−1+Fi−2for i>2.F_1=F_2=1,\qquad F_i=F_{i-1}+F_{i-2}\quad\text{for }i>2.F1​=F2​=1,Fi​=Fi−1​+Fi−2​for i>2.

The goal is to compute FnF_nFn​. A natural recursive algorithm directly follows the definition: to compute FiF_iFi​, compute Fi−1F_{i-1}Fi−1​ and Fi−2F_{i-2}Fi−2​, then add them.

The subproblems are the Fibonacci numbers FiF_iFi​ for indices from 111 through nnn. There are only nnn distinct subproblems. The trouble is that the direct recursive algorithm can compute a subproblem many times. For example, computing FnF_nFn​ requires Fn−1F_{n-1}Fn−1​ and Fn−2F_{n-2}Fn−2​, while computing Fn−1F_{n-1}Fn−1​ also requires Fn−2F_{n-2}Fn−2​. The same value is therefore recomputed in separate branches. That repetition makes the number of calls grow exponentially.

Memoization fixes the problem. Once the algorithm computes Fn−2F_{n-2}Fn−2​, it stores the result. Any later request for Fn−2F_{n-2}Fn−2​ simply retrieves that stored value. In effect, there are only nnn distinct Fibonacci subproblems to solve, and each requires just one addition beyond the work of its smaller subproblems. Under the usual assumption that these additions take constant time, the running time is Θ(n)\Theta(n)Θ(n).

This improvement comes from remembering earlier work, not from changing the Fibonacci recurrence itself. The recurrence was already correct; memoization changes how efficiently it is evaluated.

Counting time in a memoized algorithm

A useful way to analyze a memoized algorithm is to count:

  1. How many distinct subproblems there are.
  2. How much non-recursive work is done for each subproblem.

Non-recursive work means the work done to combine already-computed answers, excluding the recursive calls themselves. Those calls correspond to other subproblems and are accounted for separately.

If the set of subproblems is SSS, the total work can be bounded by

∑x∈Snon-recursive work for x.\sum_{x\in S}\text{non-recursive work for }x.x∈S∑​non-recursive work for x.

If there are NNN subproblems and each takes at most CCC non-recursive work, this gives an upper bound of NCNCNC. Thus, a polynomial number of subproblems with polynomial work per subproblem gives a polynomial-time algorithm.

A note about the size of Fibonacci numbers

The usual analysis treats addition as constant-time. That is appropriate when the numbers fit in a machine word, but Fibonacci numbers grow exponentially in their index. Writing down FnF_nFn​ therefore takes Θ(n)\Theta(n)Θ(n) bits, so later additions involve larger numbers than earlier ones.

If the machine word has www bits, an addition on numbers of about nnn bits can take on the order of ⌈n/w⌉\lceil n/w\rceil⌈n/w⌉ word operations. Using this coarse bound for each of the roughly nnn additions gives an upper bound on the order of

n+n2w.n+\frac{n^2}{w}.n+wn2​.

The precise cost depends on the computational model. The central algorithmic result remains the same: memoization reduces the exponential number of repeated recursive computations to a polynomial amount of work.

Why memoization is not always useful: merge sort again

Memoization can be applied to merge sort, but it does not help much because merge sort’s recursive calls do not repeat the same subproblems. The left and right halves are disjoint, and their descendants remain separate.

For intervals of an array of length nnn, there can be Θ(n2)\Theta(n^2)Θ(n2) possible subproblems s(i,j)s(i,j)s(i,j). If every interval were considered, and solving one took time proportional to its length, a simple memoization-based bound would be O(n3)O(n^3)O(n3). That is a valid but loose upper bound; ordinary merge sort takes Θ(nlog⁡n)\Theta(n\log n)Θ(nlogn).

This comparison gives an important lesson: memoization is valuable when a recursive computation has overlapping subproblems—the same subproblem is reached more than once. It does not automatically improve every recursive algorithm.

Think About It: What makes memoization especially effective for Fibonacci numbers but unnecessary for merge sort?

Dynamic programming and shortest paths in a DAG

A dynamic program can be viewed as a recursive algorithm with memoization. The subproblems are specified, a recurrence relates them, base cases are handled directly, and previously computed answers are stored for reuse.

Shortest paths in a directed acyclic graph provide an example where the recurrence follows naturally from the graph structure.

Let GGG be a DAG, let sss be a source vertex, and let w(u,v)w(u,v)w(u,v) be the weight of the edge from uuu to vvv. Define δ(s,v)\delta(s,v)δ(s,v) as the minimum path weight from sss to vvv. The subproblems are to compute δ(s,v)\delta(s,v)δ(s,v) for each vertex vvv.

For a vertex vvv, any path reaching vvv through an edge must first reach some predecessor uuu, then take the edge from uuu to vvv. Therefore,

δ(s,v)=min⁡(u,v)∈E(δ(s,u)+w(u,v)).\delta(s,v)=\min_{(u,v)\in E}\left(\delta(s,u)+w(u,v)\right).δ(s,v)=(u,v)∈Emin​(δ(s,u)+w(u,v)).

If no path reaches vvv, its distance is treated as ∞\infty∞. The base case is

δ(s,s)=0.\delta(s,s)=0.δ(s,s)=0.

The recurrence depends on the distances to the vertices with edges entering vvv. Since the graph is acyclic, it has a topological order. Processing vertices in that order ensures that each predecessor’s distance is available before the distance to vvv is computed.

This takes O(V+E)O(V+E)O(V+E) time: the algorithm handles each vertex and examines each edge a constant number of times. It is essentially the same computation as DAG relaxation. Relaxing each incoming edge checks whether that edge gives a better path to vvv; after all incoming edges have been considered, the smallest candidate is the minimum in the recurrence.

A memoized recursive version explores dependencies in the reverse direction: to find the answer for vvv, it asks for answers to its predecessors. The memo also acts like a record of which subproblems have already been visited. In this way, the dynamic program’s recursive exploration resembles depth-first search through the dependency graph, while the acyclic structure ensures the computation can be completed.

Think About It: Why does a topological order guarantee that the predecessor distances needed for a DAG shortest-path computation are ready?

Choosing subproblems for sequence problems

In many optimization problems, the input is a sequence. Choosing the right subproblems is often the main design challenge. Three useful choices are:

  • Prefixes: elements from the beginning through a specified position.
  • Suffixes: elements from a specified position through the end.
  • Substrings: consecutive elements between two specified positions.

For a sequence of length nnn, there are Θ(n)\Theta(n)Θ(n) prefixes and Θ(n)\Theta(n)Θ(n) suffixes. There are Θ(n2)\Theta(n^2)Θ(n2) substrings because there are two endpoints to choose. All of these give polynomially many subproblems.

A subsequence is different: it may omit elements from the middle. A sequence of length nnn has 2n2^n2n possible subsequences, because each element can either be included or omitted. That is usually too many subproblems for a straightforward polynomial-time dynamic program.

Prefixes and suffixes are often the first choices to try because they give only linearly many subproblems. Substrings can be useful when a prefix or suffix does not capture enough structure.

For a suffix-based recurrence, it is often helpful to focus on the first element of the suffix. For a prefix-based recurrence, it is often helpful to focus on the last element. For a substring, an important element may lie in the middle; removing it can split the remaining problem into two smaller substrings.

Example: maximizing a score in linear bowling

Consider nnn pins arranged in a line, with value viv_ivi​ on pin iii. A throw can knock down either one pin or two adjacent pins. Knocking down one pin iii earns viv_ivi​ points. Knocking down adjacent pins iii and i+1i+1i+1 earns the product vivi+1v_iv_{i+1}vi​vi+1​. A pin cannot be used in more than one throw, and pins may be left standing. The goal is to maximize the total score.

The values can be negative, so leaving a pin alone may be better than hitting it. On the other hand, two negative adjacent values can have a positive product, so knocking them down together can be worthwhile. The best choice depends on how the pins interact with their neighbors.

Define suffix subproblems

For each position iii, define b(i)b(i)b(i) as the maximum score obtainable from the suffix consisting of pins i,i+1,…,n−1i,i+1,\ldots,n-1i,i+1,…,n−1. This definition states the goal of the subproblem, not just a method for calculating it.

The original problem is to find b(0)b(0)b(0), because the suffix beginning at index 000 contains all the pins.

Derive the recurrence from the first pin

For the suffix beginning at iii, there are three possibilities:

  1. Leave pin iii standing. The remaining problem is the suffix beginning at i+1i+1i+1, with score b(i+1)b(i+1)b(i+1).
  2. Knock down pin iii alone. The score is viv_ivi​, and the remaining suffix again begins at i+1i+1i+1, giving vi+b(i+1)v_i+b(i+1)vi​+b(i+1).
  3. Knock down pins iii and i+1i+1i+1 together. The score is vivi+1v_iv_{i+1}vi​vi+1​, and the remaining suffix begins at i+2i+2i+2, giving vivi+1+b(i+2)v_iv_{i+1}+b(i+2)vi​vi+1​+b(i+2).

The algorithm takes the best of these choices:

b(i)=max⁡{b(i+1),  vi+b(i+1),  vivi+1+b(i+2)}.b(i)=\max\left\{b(i+1),\;v_i+b(i+1),\;v_iv_{i+1}+b(i+2)\right\}.b(i)=max{b(i+1),vi​+b(i+1),vi​vi+1​+b(i+2)}.

The third choice is available only when i+1<ni+1<ni+1<n. The base case is

b(n)=0,b(n)=0,b(n)=0,

because an empty suffix contains no pins and earns no points.

There are only Θ(n)\Theta(n)Θ(n) suffix subproblems. Each takes constant non-recursive work: a few additions, a product, and a maximum. Therefore, the memoized algorithm runs in Θ(n)\Theta(n)Θ(n) time, assuming the pin values and the relevant arithmetic fit the chosen constant-time model.

The topological order and a bottom-up version

The recurrence for b(i)b(i)b(i) depends on b(i+1)b(i+1)b(i+1) and sometimes b(i+2)b(i+2)b(i+2). Those are suffixes beginning later in the sequence, so they are smaller remaining problems. The correct order is therefore decreasing index: compute b(n)b(n)b(n) first, then b(n−1)b(n-1)b(n−1), and continue back to b(0)b(0)b(0).

This order makes it possible to avoid recursive calls entirely. A bottom-up dynamic program fills a table in topological order:

b[n] = 0

for i from n - 1 down to 0:
    b[i] = max(b[i + 1], v[i] + b[i + 1])
    if i + 1 < n:
        b[i] = max(b[i], v[i] * v[i + 1] + b[i + 2])

return b[0]

This is the same dynamic program as the memoized recursive version, but it computes the subproblems explicitly in order. Bottom-up implementations are often fast and straightforward when the topological order can be written as a loop.

Why local choices do not make the algorithm exponential

At each pin, the algorithm considers every possible local action: skip the pin, take it alone, or pair it with the next pin. This is a form of local brute force. Trying combinations of choices independently across the whole sequence could require exponentially many strategies.

Dynamic programming avoids that explosion because every choice leads to one of a small number of suffix subproblems, and each suffix answer is computed only once. The algorithm still compares all relevant local options, but it reuses the results of the remaining problems instead of re-exploring them for every possible history.

This pattern is common in optimization problems. The recurrence identifies the possible first decisions, uses a smaller subproblem to represent what remains, and combines the alternatives with a maximum or minimum. Maximization problems commonly use max⁡\maxmax; minimization problems commonly use min⁡\minmin. Other problems may combine alternatives in different ways, such as with logical “or” or “and.”

Think About It: In the bowling problem, why is it enough to consider what happens to the first pin of each suffix?

A complete review of the design process

SRTBOT organizes recursive algorithm design by asking for subproblems, relations, a topological order, base cases, the original problem, and a running-time analysis. The subproblems and their dependencies form a graph, and an acyclic dependency structure allows the subproblems to be evaluated in a safe order.

Dynamic programming adds memoization to recursion. It is most useful when recursive branches overlap and ask for the same subproblems repeatedly. Fibonacci computation demonstrates the difference: direct recursion repeats work exponentially many times, while memoization solves only the linearly many distinct indexed problems. DAG shortest paths demonstrate how a recurrence can use graph predecessors and a topological order. The bowling problem shows how to invent a recurrence for a new optimization task by defining suffix subproblems and considering the possible decisions at the first position.

For a memoized dynamic program, the running-time analysis follows the distinct subproblems and the non-recursive work for each one. When both are polynomial, the resulting computation is polynomial as well. The central design challenge is finding a compact set of subproblems that preserves enough information to express the original problem through smaller ones.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent