Skip to lesson

What dynamic programming is

Dynamic programming solves optimization problems by breaking them into overlapping subproblems and storing intermediate answers.

The core intuition of dynamic programming

Dynamic programming solves a problem by breaking it into overlapping subproblems, solving each subproblem once and storing its answer to reuse it.

Pure recursive algorithms often solve identical subproblems repeatedly. This redundant work causes exponential runtime explosions on modest inputs. Dynamic programming replaces repeated calculation with systematic table lookups.

Step by step

Step 1 of 5

Array: 0, 1.
idx
1
val
1
Compute fib(0) and fib(1) as initial base cases.

Example 1 · Recursive Fibonacci Call Counter

FibonacciComparison.javaJava
public class FibonacciComparison {    static int naiveCalls = 0;    static int memoCalls = 0;
    static int naiveFib(int n) {        naiveCalls++;        if (n <= 1) return n;        return naiveFib(n - 1) + naiveFib(n - 2);    }
    static int memoFib(int n, int[] memo) {        memoCalls++;        if (n <= 1) return n;        if (memo[n] != 0) return memo[n];        memo[n] = memoFib(n - 1, memo) + memoFib(n - 2, memo);        return memo[n];    }
    public static void main(String[] args) {        int n = 7;        int res1 = naiveFib(n);        int[] memo = new int[n + 1];        int res2 = memoFib(n, memo);        System.out.println("Result: " + res1 + " " + res2);        System.out.println("Naive calls: " + naiveCalls);        System.out.println("Memo calls: " + memoCalls);    }}
Output
Result: 13 13
Naive calls: 41
Memo calls: 13

What this code does

  • Naive recursion recalculates subtrees repeatedly, producing 41 function calls for n = 7.
  • Memoization caches subproblem outputs, lowering invocation count to 13 calls.
  • Both approaches produce the identical final Fibonacci number 13.

Consider computing the nth Fibonacci number with standard naive recursion. The function splits into two smaller calls at every step. Computing fib(5) calculates fib(3) twice and fib(2) three times. Caching each result shrinks the call tree to linear size. Subsequent requests return previously computed values in O(1) time. This transformation reduces time complexity from O(2^n) to O(n).

Predict the output

Count the repeated calls

Read the program and choose what it prints.

Round 1 of 2

Every call to fib adds 1 to calls. What does this print?

public class FibCount4 {
static int calls = 0;
static int fib(int n) {
calls++;
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
public static void main(String[] args) {
fib(4);
System.out.println(calls);
}
}

Two core requirements for dynamic programming

Dynamic programming applies only when a problem exhibits two mathematical properties. The first property is overlapping subproblems across search paths. The second property is optimal substructure in solutions.

Example 2 · Min Cost Stairs: Optimal Substructure

MinimumCostWalk.javaJava
public class MinimumCostWalk {    public static int minCost(int[] cost) {        int n = cost.length;        int[] dp = new int[n];        dp[0] = cost[0];        dp[1] = cost[1];        for (int i = 2; i < n; i++) {            dp[i] = cost[i] + Math.min(dp[i - 1], dp[i - 2]);        }        return Math.min(dp[n - 1], dp[n - 2]);    }
    public static void main(String[] args) {        int[] cost = {10, 15, 20};        System.out.println("Min cost: " + minCost(cost));        int[] cost2 = {1, 100, 1, 1, 1, 100, 1, 1, 100, 1};        System.out.println("Min cost 2: " + minCost(cost2));    }}
Output
Min cost: 15
Min cost 2: 6

What this code does

  • Each step considers arriving from either one or two steps earlier.
  • The cheapest cost to reach step i is built from the cheapest costs to reach steps i - 1 and i - 2. This is optimal substructure.
  • Checking the final two steps yields minimum cost 15 and 6 respectively.

Example 3 · Stair Paths: Overlapping Subproblems

ClimbingStairsWays.javaJava
public class ClimbingStairsWays {    public static int countWays(int n) {        if (n <= 2) return n;        int[] dp = new int[n + 1];        dp[1] = 1;        dp[2] = 2;        for (int i = 3; i <= n; i++) {            dp[i] = dp[i - 1] + dp[i - 2];        }        return dp[n];    }
    public static void main(String[] args) {        System.out.println("Ways for 3 steps: " + countWays(3));        System.out.println("Ways for 4 steps: " + countWays(4));        System.out.println("Ways for 5 steps: " + countWays(5));    }}
Output
Ways for 3 steps: 3
Ways for 4 steps: 5
Ways for 5 steps: 8

What this code does

  • Reaching step i requires stepping from step i - 1 or step i - 2.
  • Plain recursion would count the ways to step 3 inside both step 5 and step 4. The table stores each answer once, so the overlap is solved once.
  • Values for steps 3, 4, and 5 produce 3, 5, and 8 ways.

Overlapping subproblems mean smaller sub-problems recur frequently during recursion. Merge sort breaks inputs into independent halves without overlap. Divide and conquer suits independent subproblems rather than dynamic programming. Optimal substructure means optimal solutions contain optimal solutions to subproblems. Shortest path algorithms build complete paths from shortest sub-paths. If subproblem choices interact and corrupt each other, dynamic programming fails.

Contrasting dynamic programming with greedy algorithms

Greedy algorithms make a single locally optimal choice at each step. They never backtrack or examine alternate decisions later. Greedy strategies require strict mathematical proofs to guarantee global optimality.

Dynamic programming examines all viable transitions systematically. It avoids exponential explosion by recording subproblem answers in tables. Use dynamic programming when local greedy choices fail to produce global optimums.

Consider making change for six cents using coins four, three, and one. A greedy choice picks four first, requiring three coins total. Dynamic programming explores both choices and correctly finds two three-cent coins.

Next step

Check your understanding

10 quick questions