Open main menu
Figure 1. Finding the shortest path in a graph using optimal substructure; a straight line indicates a single edge; a wavy line indicates a shortest path between the two vertices it connects (among other paths, not shown, sharing the same two vertices); the bold line is the overall shortest path from start to goal.

Dynamic programming is both a mathematical optimization method and a computer programming method. The method was developed by Richard Bellman in the 1950s and has found applications in numerous fields, from aerospace engineering to economics. In both contexts it refers to simplifying a complicated problem by breaking it down into simpler sub-problems in a recursive manner. While some decision problems cannot be taken apart this way, decisions that span several points in time do often break apart recursively. Likewise, in computer science, if a problem can be solved optimally by breaking it into sub-problems and then recursively finding the optimal solutions to the sub-problems, then it is said to have optimal substructure.

If sub-problems can be nested recursively inside larger problems, so that dynamic programming methods are applicable, then there is a relation between the value of the larger problem and the values of the sub-problems.[1] In the optimization literature this relationship is called the Bellman equation.



Mathematical optimizationEdit


Control theoryEdit

In control theory, a typical problem is to find an admissible control   which causes the system   to follow an admissible trajectory   on a continuous time interval   that minimizes a cost function


The solution to this problem is an optimal control law or policy  , which produces an optimal trajectory   and an optimized loss function  . The latter obeys the fundamental equation of dynamic programming:


a partial differential equation known as the Hamilton–Jacobi–Bellman equation, in which   and  . One finds the minimizing   in terms of  ,  , and the unknown function   and then substitutes the result into the Hamilton–Jacobi–Bellman equation to get the partial differential equation to be solved with boundary condition  .[2] In practice, this generally requires numerical techniques for some discrete approximation to the exact optimization relationship.

Alternatively, the continuous process can be approximated by a discrete system, which leads to a following recurrence relation analog to the Hamilton–Jacobi–Bellman equation:


at the  -th stage of   equally spaced discrete time intervals, and where   and   denote discrete approximations to   and  . This functional equation is known as the Bellman equation, which can be solved for an exact solution of the discrete approximation of the optimization equation.[3]

Example from economics: Ramsey's problem of optimal savingEdit

In economics, the objective is generally to maximize (rather than minimize) some dynamic social welfare function. In Ramsey's problem, this function relates amounts of consumption to levels of utility. Loosely speaking, the planner faces the trade-off between contemporaneous consumption and future consumption (via investment in capital stock that is used in production), known as intertemporal choice. Future consumption is discounted at a constant rate  . A discrete approximation to the transition equation of capital is given by


where   is consumption,   is capital, and   is a production function satisfying the Inada conditions. An initial capital stock   is assumed.

Let   be consumption in period t, and assume consumption yields utility   as long as the consumer lives. Assume the consumer is impatient, so that he discounts future utility by a factor b each period, where  . Let   be capital in period t. Assume initial capital is a given amount  , and suppose that this period's capital and consumption determine next period's capital as  , where A is a positive constant and  . Assume capital cannot be negative. Then the consumer's decision problem can be written as follows:

  subject to   for all  

Written this way, the problem looks complicated, because it involves solving for all the choice variables  . (Note that   is not a choice variable—the consumer's initial capital is taken as given.)

The dynamic programming approach to solve this problem involves breaking it apart into a sequence of smaller decisions. To do so, we define a sequence of value functions  , for   which represent the value of having any amount of capital k at each time t. Note that  , that is, there is (by assumption) no utility from having capital after death.

The value of any quantity of capital at any previous time can be calculated by backward induction using the Bellman equation. In this problem, for each  , the Bellman equation is

  subject to  

This problem is much simpler than the one we wrote down before, because it involves only two decision variables,   and  . Intuitively, instead of choosing his whole lifetime plan at birth, the consumer can take things one step at a time. At time t, his current capital   is given, and he only needs to choose current consumption   and saving  .

To actually solve this problem, we work backwards. For simplicity, the current level of capital is denoted as k.   is already known, so using the Bellman equation once we can calculate  , and so on until we get to  , which is the value of the initial decision problem for the whole lifetime. In other words, once we know  , we can calculate  , which is the maximum of  , where   is the choice variable and  .

Working backwards, it can be shown that the value function at time   is


where each   is a constant, and the optimal amount to consume at time   is


which can be simplified to



Computer programmingEdit

There are two key attributes that a problem must have in order for dynamic programming to be applicable: optimal substructure and overlapping sub-problems. If a problem can be solved by combining optimal solutions to non-overlapping sub-problems, the strategy is called "divide and conquer" instead.[1] This is why merge sort and quick sort are not classified as dynamic programming problems.


Overlapping sub-problems means that the space of sub-problems must be small, that is, any recursive algorithm solving the problem should solve the same sub-problems over and over, rather than generating new sub-problems. For example, consider the recursive formulation for generating the Fibonacci series: Fi = Fi−1 + Fi−2, with base case F1 = F2 = 1. Then F43F42 + F41, and F42F41 + F40. Now F41 is being solved in the recursive sub-trees of both F43 as well as F42. Even though the total number of sub-problems is actually small (only 43 of them), we end up solving the same problems over and over if we adopt a naive recursive solution such as this. Dynamic programming takes account of this fact and solves each sub-problem only once.



  • Top-down approach: This is the direct fall-out of the recursive formulation of any problem. If the solution to any problem can be formulated recursively using the solution to its sub-problems, and if its sub-problems are overlapping, then one can easily memoize or store the solutions to the sub-problems in a table. Whenever we attempt to solve a new sub-problem, we first check the table to see if it is already solved. If a solution has been recorded, we can use it directly, otherwise we solve the sub-problem and add its solution to the table.
  • Bottom-up approach: Once we formulate the solution to a problem recursively as in terms of its sub-problems, we can try reformulating the problem in a bottom-up fashion: try solving the sub-problems first and use their solutions to build-on and arrive at solutions to bigger sub-problems. This is also usually done in a tabular form by iteratively generating solutions to bigger and bigger sub-problems by using the solutions to small sub-problems. For example, if we already know the values of F41 and F40, we can directly calculate the value of F42.

Some programming languages can automatically memoize the result of a function call with a particular set of arguments, in order to speed up call-by-name evaluation (this mechanism is referred to as call-by-need). Some languages make it possible portably (e.g. Scheme, Common Lisp, Perl or D). Some languages have automatic memoization built in, such as tabled Prolog and J, which supports memoization with the M. adverb.[4] In any case, this is only possible for a referentially transparent function. Memoization is also encountered as an easily accessible design pattern within term-rewrite based languages such as Wolfram Language.


Dynamic programming is widely used in bioinformatics for the tasks such as sequence alignment, protein folding, RNA structure prediction and protein-DNA binding. The first dynamic programming algorithms for protein-DNA binding were developed in the 1970s independently by Charles DeLisi in USA[5] and Georgii Gurskii and Alexander Zasedatelev in USSR.[6] Recently these algorithms have become very popular in bioinformatics and computational biology, particularly in the studies of nucleosome positioning and transcription factor binding.

Examples: Computer algorithmsEdit

Dijkstra's algorithm for the shortest path problemEdit

From a dynamic programming point of view, Dijkstra's algorithm for the shortest path problem is a successive approximation scheme that solves the dynamic programming functional equation for the shortest path problem by the Reaching method.[7][8][9]

In fact, Dijkstra's explanation of the logic behind the algorithm,[10] namely




Fibonacci sequenceEdit


   function fib(n)
       if n <= 1 return n


  1. fib(5)
  2. fib(4) + fib(3)



   function fib(n)
       if key n is not in map m 
       return m[n]



   function fib(n)
       if n = 0
           return 0
           var previousFib := 0, currentFib := 1
               var newFib := previousFib + currentFib
               previousFib := currentFib
               currentFib  := newFib
       return currentFib


Note that the above method actually takes   time for large n because addition of two integers with   bits each takes   time. (The nth fibonacci number has   bits.) Also, there is a closed form for the Fibonacci sequence, known as Binet's formula, from which the  -th term can be computed in approximately   time, which is more efficient than the above dynamic programming technique. However, the simple recurrence directly gives the matrix form that leads to an approximately   algorithm by fast matrix exponentiation.

A type of balanced 0–1 matrixEdit

Consider the problem of assigning values, either zero or one, to the positions of an n × n matrix, with n even, so that each row and each column contains exactly n / 2 zeros and n / 2 ones. We ask how many different assignments there are for a given  . For example, when n = 4, four possible solutions are



Brute force consists of checking all assignments of zeros and ones and counting those that have balanced rows and columns (n / 2 zeros and n / 2 ones). As there are   possible assignments, this strategy is not practical except maybe up to  .




  0      1      0      1              0      0      1      1

  1      0      1      0              0      0      1      1

  0      1      0      1              1      1      0      0

  1      0      1      0              1      1      0      0


The number of solutions (sequence A058527 in the OEIS) is




Consider a checkerboard with n × n squares and a cost function c(i, j) which returns a cost associated with square (i,j) (i being the row, j being the column). For instance (on a 5 × 5 checkerboard),

5 6 7 4 7 8
4 7 6 1 1 4
3 3 5 7 8 2
2 6 7 0
1 *5*
1 2 3 4 5

Thus c(1, 3) = 5

Let us say there was a checker that could start at any square on the first rank (i.e., row) and you wanted to know the shortest path (the sum of the minimum costs at each visited rank) to get to the last rank; assuming the checker could move only diagonally left forward, diagonally right forward, or straight forward. That is, a checker on (1,3) can move to (2,2), (2,3) or (2,4).

2 x x x
1 o
1 2 3 4 5



Starting at rank n and descending to rank 1, we compute the value of this function for all the squares at each successive rank. Picking the square that holds the minimum value at each rank gives us the shortest path between rank n and rank 1.


4 A
3 B C D
1 2 3 4 5



The first line of this equation deals with a board modeled as squares indexed on 1 at the lowest bound and n at the highest bound. The second line specifies what happens at the last rank; providing a base case. The third line, the recursion, is the important part. It represents the A,B,C,D terms in the example. From this definition we can derive straightforward recursive code for q(i, j). In the following pseudocode, n is the size of the board, c(i, j) is the cost function, and min() returns the minimum of a number of values:

function minCost(i, j)
    if j < 1 or j > n
        return infinity
    else if i = 1
        return c(i, j)

This function only computes the path cost, not the actual path. We discuss the actual path below. This, like the Fibonacci-numbers example, is horribly slow because it too exhibits the overlapping sub-problems attribute. That is, it recomputes the same path costs over and over. However, we can compute it much faster in a bottom-up fashion if we store path costs in a two-dimensional array q[i, j] rather than using a function. This avoids recomputation; all the values needed for array q[i, j] are computed ahead of time only once. Precomputed values for (i,j) are simply looked-up whenever needed.

We also need to know what the actual shortest path is. To do this, we use another array p[i, j]; a predecessor array. This array records the path to any square s. The predecessor of s is modeled as an offset relative to the index (in q[i, j]) of the precomputed path cost of s. To reconstruct the complete path, we lookup the predecessor of s, then the predecessor of that square, then the predecessor of that square, and so on recursively, until we reach the starting square. Consider the following code:

 function computeShortestPathArrays()
     for x from 1 to n
     for y from 1 to n
         q[y, 0]     := infinity
         q[y, n + 1] := infinity
     for y from 2 to n
         for x from 1 to n
                 p[y, x] := -1
             else if m = q[y-1, x]
                 p[y, x] :=  0
                 p[y, x] :=  1


 function computeShortestPath()
     minIndex := 1
     min := q[n, 1]
     for i from 2 to n
         if q[n, i] < min
             minIndex := i
             min := q[n, i]
     printPath(n, minIndex)
 function printPath(y, x)
     if y = 2
         print(x + p[y, x])

Sequence alignmentEdit

In genetics, sequence alignment is an important application where dynamic programming is essential.[11] Typically, the problem consists of transforming one sequence into another using edit operations that replace, insert, or remove an element. Each operation has an associated cost, and the goal is to find the sequence of edits with the lowest total cost.





Tower of Hanoi puzzleEdit




  • Only one disk may be moved at a time.

The dynamic programming solution consists of solving the functional equation






Egg dropping puzzleEdit

The following is a description of the instance of this famous puzzle involving N=2 eggs and a building with H=36 floors:[13]

Suppose that we wish to know which stories in a 36-story building are safe to drop eggs from, and which will cause the eggs to break on landing (using U.S. English terminology, in which the first floor is at ground level). We make a few assumptions:
  • An egg that survives a fall can be used again.
  • A broken egg must be discarded.




Now, let


Then it can be shown that[14]


with W(n,0) = 0 for all n > 0 and W(1,k) = k for all k. It is easy to solve this equation iteratively by systematically increasing the values of n and k.


Faster DP solution using a different parametrizationEdit

Notice that the above solution takes   time with a DP solution. This can be improved to   time by binary searching on the optimal   in the above recurrence, since   is increasing in   while   is decreasing in  , thus a local minimum of   is a global minimum. Also, by storing the optimal   for each cell in the DP table and referring to its value for the previous cell, the optimal   for each cell can be found in constant time, improving it to   time. However, there is an even faster solution that involves a different parametrization of the problem:

Let   be the total number of floors such that the eggs break when dropped from the  th floor (The example above is equivalent to taking  ).

Let   be the minimum floor from which the egg must be dropped to be broken.

Let   be the maximum number of values of   that are distinguishable using   tries and   eggs.

Then   for all  .

Let   be the floor from which the first egg is dropped in the optimal strategy.

If the first egg broke,   is from   to   and distinguishable using at most   tries and   eggs.

If the first egg did not break,   is from   to   and distinguishable using   tries and   eggs.

Therefore,  .

Then the problem is equivalent to finding the minimum   such that  .

To do so, we could compute   in order of increasing  , which would take   time.

Thus, if we separately handle the case of  , the algorithm would take   time.

But the recurrence relation can in fact be solved, giving  , which can be computed in   time using the identity   for all  .

Since   for all  , we can binary search on   to find  , giving an   algorithm. [15]

Matrix chain multiplicationEdit

Matrix chain multiplication is a well-known example that demonstrates utility of dynamic programming. For example, engineering applications often have to multiply a chain of matrices. It is not surprising to find matrices of large dimensions, for example 100×100. Therefore, our task is to multiply matrices  . As we know from basic linear algebra, matrix multiplication is not commutative, but is associative; and we can multiply only two matrices at a time. So, we can multiply this chain of matrices in many different ways, for example:









The formula is:


where k ranges from i to j − 1.

  •   is the row dimension of matrix i,
  •   is the column dimension of matrix k,
  •   is the column dimension of matrix j.


 function OptimalMatrixChainParenthesis(chain)
     n = length(chain)
     for i = 1, n
         m[i,i] = 0    // Since it takes no calculations to multiply one matrix
     for len = 2, n
         for i = 1, n - len + 1
             j = i + len -1
             m[i,j] = infinity      // So that the first calculation updates
             for k = i, j-1
                 if q < m[i, j]     // The new order of parentheses is better than what we had
                     m[i, j] = q    // Update
                     s[i, j] = k    // Record which k to split on, i.e. where to place the parenthesis




 function PrintOptimalParenthesis(s, i, j)
     if i = j
        print "A"i




      if i < j
         return MatrixMultiply(LeftSide, RightSide) 
      else if i = j
         return Ai   // matrix at position i
         print "error, i <= j must hold"

      if columns(A) = rows(B) 
         for i = 1, rows(A)
            for j = 1, columns(B)
               C[i, j] = 0
               for k = 1, columns(A)
               return C 
          print "error, incompatible dimensions."



Bellman explains the reasoning behind the term dynamic programming in his autobiography, Eye of the Hurricane: An Autobiography (1984, page 159). He explains:


The word dynamic was chosen by Bellman to capture the time-varying aspect of the problems, and because it sounded impressive.[11] The word programming referred to the use of the method to find an optimal program, in the sense of a military schedule for training or logistics. This usage is the same as that in the phrases linear programming and mathematical programming, a synonym for mathematical optimization.[17]

The above explanation of the origin of the term is lacking. As Russell and Norvig in their book have written, referring to the above story: "This cannot be strictly true, because his first paper using the term (Bellman, 1952) appeared before Wilson became Secretary of Defense in 1953.[18] Also, there is a comment in a speech by Harold J. Kushner, where he remembers Bellman. Quoting Kushner as he speaks of Bellman: "On the other hand, when I asked him the same question, he replied that he was trying to upstage Dantzig's linear programming by adding dynamic. Perhaps both motivations were true."

Algorithms that use dynamic programmingEdit

See alsoEdit


  2. ^ Kamien, M. I.; Schwartz, N. L. (1991). Dynamic Optimization: The Calculus of Variations and Optimal Control in Economics and Management (Second ed.). New York: Elsevier. p. 261. ISBN 978-0-444-01609-6.
  3. ^ Kirk, Donald E. (1970). Optimal Control Theory: An Introduction. Englewood Cliffs, NJ: Prentice-Hall. pp. 94–95. ISBN 978-0-13-638098-6.
  7. ^ Sniedovich, M. (2006), "Dijkstra's algorithm revisited: the dynamic programming connexion" (PDF), Journal of Control and Cybernetics, 35 (3): 599–620. Online version of the paper with interactive computational modules.
  10. ^ Dijkstra 1959, p. 270
  11. ^ a b Eddy, S. R. (2004). "What is Dynamic Programming?". Nature Biotechnology. 22 (7): 909–910. doi:10.1038/nbt0704-909. PMID 15229554.
  12. ^ Moshe Sniedovich (2002), "OR/MS Games: 2. The Towers of Hanoi Problem", INFORMS Transactions on Education, 3 (1): 34–51.
  15. ^ Dean Connable Wills, Connections between combinatorics of permutations and algorithms and geometry
  16. ^ Stuart Dreyfus. "Richard Bellman on the birth of Dynamical Programming".
  17. ^ Nocedal, J.; Wright, S. J. (2006). Numerical Optimization. Springer. p. 9.
  18. ^ Russell, S.; Norvig, P. (2009). Artificial Intelligence: A Modern Approach (3rd ed.). Prentice Hall. ISBN 978-0-13-207148-2.

Further readingEdit

External linksEdit