Stop 10 · Data Structures & Algorithms in JavaTopics · 11/11

Dynamic Programming Basics

Part of the Java Roadmap

In short

DP sounds scary, but the core idea is simple: never solve the same small problem twice. Write it down once, and reuse it. That turns some exponential solutions into fast linear ones.

Dynamic programming solves problems with overlapping subproblems by storing results, either top-down with memoisation or bottom-up with a table.

The jaadu flips open a well-worn notebook full of answers and points at one, while a pile of crumpled rough work lies forgotten nearby.

Think of it like this

The notebook of sums

Your teacher asks for 47 × 12. You work it out and jot it in your notebook. Five minutes later the same question appears in another problem, and you just read the answer. DP is keeping that notebook, so repeated sub-questions cost nothing.

Watch it happen

Fewest coins for each amount, coins {1, 2, 5}

0
0
∞
1
∞
2
∞
3
∞
4
∞
5
∞
6

1/5dp[a] will hold the fewest coins that make amount a. dp[0] = 0, everything else starts as infinity.

The big ideas

What you need to know

Overlapping subproblems

Plain recursive fib(n) recalculates fib(n - 2) again and again. DP stores each result once.

Optimal substructure

The best answer for n is built from best answers to smaller inputs, like dp[a] from dp[a - coin].

Top-down: memoisation

Keep the natural recursion and add a cache (array or HashMap). Easy to write from a brute-force solution.

Bottom-up: tabulation

Fill a table from the smallest case upwards with loops. No recursion depth limits, and often easy to shrink memory.

How it works

Solving a DP problem

  1. 1

    Define the state

    Say in words what dp[i] means, for example 'fewest coins to make amount i'.

  2. 2

    Find the recurrence

    How does dp[i] come from smaller states? dp[i] = min(dp[i - coin] + 1).

  3. 3

    Set base cases

    dp[0] = 0, and impossible states marked clearly.

  4. 4

    Choose the order

    Fill the table so every state you read is already computed.

  5. 5

    Read the answer

    Usually dp[n], or the best value across the table.

See it in code

Walk through the code

java
1import java.util.Arrays;2 3public class DPBasics {4    // Top-down: plain recursion plus a memo array5    static long[] memo = new long[91];6 7    static long fib(int n) {8        if (n <= 1) return n;9        if (memo[n] != 0) return memo[n];10        return memo[n] = fib(n - 1) + fib(n - 2);11    }12 13    // Bottom-up: fewest coins to make an amount14    static int minCoins(int[] coins, int amount) {15        int[] dp = new int[amount + 1];16        Arrays.fill(dp, Integer.MAX_VALUE);17        dp[0] = 0;18        for (int a = 1; a <= amount; a++) {19            for (int c : coins) {20                if (c <= a && dp[a - c] != Integer.MAX_VALUE) {21                    dp[a] = Math.min(dp[a], dp[a - c] + 1);22                }23            }24        }25        return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];26    }27 28    public static void main(String[] args) {29        System.out.println(fib(90));                                // 288006719437081612030        System.out.println(minCoins(new int[] {1, 2, 5, 10}, 18));  // 4 (10 + 5 + 2 + 1)31    }32}

1/4Same recursion as before, but each fib(n) is stored the first time and then just read.

Memoised Fibonacci and bottom-up coin change. Without the memo, fib(90) would take far longer than your lifetime.

Save yourself the pain

Common mistakes

Oops

Writing dp[a - c] + 1 without checking for MAX_VALUE.

Do this instead

Integer.MAX_VALUE + 1 overflows to a huge negative number and wins every min. Check first, or use amount + 1 as infinity.

Oops

Using greedy (biggest coin first) for every coin system.

Do this instead

Greedy fails for coins like {1, 3, 4} and amount 6. DP finds 3 + 3, greedy picks 4 + 1 + 1.

Oops

Jumping into code before defining what dp[i] means.

Do this instead

Write the state in one sentence first. Most DP bugs come from a fuzzy state.

Your mission

First five DP problems

~90 min

Quick check

What does memoisation add to a recursive solution?

Go deeper

  1. 1Solve Fibonacci with memoisation and then bottom-up.
  2. 2Solve climbing stairs, coin change and longest common subsequence.
  3. 3For each problem, write down the state and the transition before coding.

Also part of these roadmaps

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge