Tech Interview RoomStudy guides

Dynamic Programming

Coin change: minimum number of coins to make an amount (dynamic programming).

Intermediate · 2 min read · Lesson 2 of 6 in Dynamic Programming

Problem

Given coin denominations and an amount, return the fewest coins needed, or -1 if impossible. Coins [1, 2, 5], amount 11 → 3 (5 + 5 + 1).

Approach

Greedy fails for arbitrary denominations (coins [1, 3, 4], amount 6: greedy gives 4+1+1 = 3 coins; optimal is 3+3 = 2). Use bottom-up DP: dp[a] = minimum coins for amount a; dp[0] = 0; dp[a] = min over coins c ≤ a of dp[a - c] + 1.

java
import java.util.Arrays;

class CoinChange {
    static int minCoins(int[] coins, int amount) {
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int a = 1; a <= amount; a++) {
            for (int c : coins) {
                if (c <= a && dp[a - c] != Integer.MAX_VALUE) dp[a] = Math.min(dp[a], dp[a - c] + 1);
            }
        }
        return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
    }

    // Variant: number of distinct combinations (order does not matter)
    static long ways(int[] coins, int amount) {
        long[] dp = new long[amount + 1];
        dp[0] = 1;
        for (int c : coins)                       // coins in the outer loop avoids counting permutations
            for (int a = c; a <= amount; a++) dp[a] += dp[a - c];
        return dp[amount];
    }

    public static void main(String[] args) {
        System.out.println(minCoins(new int[] {1, 2, 5}, 11));  // 3
        System.out.println(minCoins(new int[] {1, 3, 4}, 6));   // 2
        System.out.println(minCoins(new int[] {2}, 3));         // -1
        System.out.println(ways(new int[] {1, 2, 5}, 5));       // 4
    }
}

Complexity

O(amount × number of coins) time; O(amount) space.

Follow-up questions interviewers ask

Try answering each one before you open it.

How do you recognise that a problem needs dynamic programming?

Two signs: optimal substructure (the best answer is built from best answers to smaller subproblems) and overlapping subproblems (the same subproblem is solved many times in a naive recursion). Start with a recursive definition, add memoisation, then convert to a bottom-up table and reduce space if only the last row or few values are needed.

How would you also return which coins were used?

Keep a parent[a] array recording the coin chosen when dp[a] was improved. After filling the table, walk back from amount: append parent[a], set a -= parent[a], until 0.