Coin Change

Find the fewest coins that add up to an amount, building on the answers for smaller amounts.

Given a list of coin values coins and a target amount, return the fewest coins that add up to exactly amount, or -1 if no mix of the coins can make it. There are as many coins of each value as you need.

Example 1
Input: coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 5 + 5 + 1.
Example 2
Input: coins = [2], amount = 3
Output: -1
Example 3
Input: coins = [1], amount = 0
Output: 0
Solution

The Idea

Think of paying exactly 11 at a shop counter with coins worth 1, 2 and 5, using as few coins as you can. Most people reach for the biggest coin that still fits: 5, then 5 again, then 1. That is three coins, and Example 1 says three is the best.

Now change the coins to 1, 3 and 4 and pay 6. The biggest coin first gives 4, then 1 and 1, three coins. Yet 3 + 3 pays 6 with two. So reaching for the biggest coin can go wrong, and listing every mix of coins gets long quickly as the amount grows. How can we be sure of the fewest coins without trying every mix?

Look at the last coin instead of the first. Any way of paying 11 with coins 1, 2 and 5 ends with one of them. If the last coin is 5, the coins before it pay 6, and they should be the fewest coins that pay 6. In the same way, a last coin of 2 leaves 9, and a last coin of 1 leaves 10.

So if we already knew the fewest coins for 10, 9 and 6, the answer for 11 would be one more than the smallest of those three. Each of them is found the same way, from even smaller amounts, down to 0, which takes no coins at all. Look at the picture below.

A row of boxes labelled fewest coins, one for each amount from 0 to 11, with coins 1, 2 and 5: 0, 1, 1, 2, 2, 1, 2, 2, 3, 3, 2, 3. Arrows labelled + coin 1, + coin 2 and + coin 5 lead from amounts 10, 9 and 6 to amount 11, which gets 1 + smallest of 2, 3 and 2 = 3.

The row labelled fewest coins has one box for every amount from 0 to 11. The box for 6 holds 2 (5 + 1), the box for 9 holds 3 (5 + 2 + 2), and the box for 10 holds 2 (5 + 5). The arrows labelled + coin 1, + coin 2 and + coin 5 lead from these boxes to 11. The smallest of 2, 3 and 2 is 2, so 11 needs 3 coins.

Working out the small amounts first, and building each new answer from answers already written down, is called dynamic programming. Here the written-down answers live in an array named dp, where dp[a] is the fewest coins that make amount a. In that notation, the picture shows dp[11] = 1 + min(dp[10], dp[9], dp[6]).

Solution Approach

Turning that idea into code means settling three things: whether to run the last-coin rule with recursion or with the dp array, the order in which to fill the array, and a mark for amounts that no mix of coins makes.

Trying every last coin with recursion

Why not write the last-coin rule as a method that calls itself? To find the fewest coins for 11, it would call itself for 10, 9 and 6, and each of those calls would do the same for its own smaller amounts. That gives the right answer, but the same amounts come up again and again. For coins 1, 2 and 5 and amount 11, such a method makes 527 calls, and it works out the answer for 6 nine separate times.

Storing each answer the first time it is worked out, so that the second request for amount 6 just reads it back, is called memoization. It cuts the work to one calculation per amount. The dp array does the same remembering without any recursion, by filling the answers in order.

Filling the array from 0 upward

In what order should the entries be filled? The entry for an amount only reads entries for smaller amounts: the amount minus one of the coins. So filling dp[0], dp[1], dp[2] and so on in order means every entry an amount needs is already there by the time that amount comes up. The entry dp[0] is 0, because paying nothing takes no coins.

For each amount, every coin gets a turn as the last coin. A coin bigger than the amount is skipped: 5 cannot be the last coin of 3, since 3 - 5 is negative and has no entry.

Marking amounts that cannot be made

What goes in the entry for an amount that no mix of coins makes? Example 2 has two of them: with only coins of 2, neither 1 nor 3 can be paid. Such an entry needs a value bigger than any real answer, so that taking the smaller of two counts never picks it over a real one.

No real answer needs more coins than the amount itself, which is the count when every coin is worth 1 (11 coins of 1 pay 11), so amount + 1 works. The code calls it impossible, fills every entry with it at the start, and returns -1 if dp[amount] still holds it at the end.

Java Solution

The method coinChange works in these steps:

  1. First, set impossible to amount + 1. Create the array dp with one entry for each amount from 0 to amount, fill it with impossible using Arrays.fill, and then set dp[0] to 0.
  2. A loop moves a from 1 up to amount. Inside it, a second loop takes each coin from coins in turn.
  3. For a coin no bigger than a, dp[a - coin] + 1 is the number of coins when that coin is paid last. The call Math.min keeps the smaller of that count and the current dp[a].
  4. When both loops are done, return -1 if dp[amount] still equals impossible, and dp[amount] otherwise.

A small helper, show, prints each input with its answer. The main method calls it for the three examples and three more cases: coins 1, 3 and 4 with amount 6, coins 3 and 7 with amount 11, and coins 2, 5, 10 and 1 with amount 27.

Java
import java.util.Arrays;

public class CoinChange {

    public static int coinChange(int[] coins, int amount) {
        int impossible = amount + 1;        // more coins than any real answer needs
        int[] dp = new int[amount + 1];     // dp[a]: fewest coins that make amount a
        Arrays.fill(dp, impossible);
        dp[0] = 0;                          // amount 0 needs no coins
        for (int a = 1; a <= amount; a++) {
            for (int coin : coins) {
                if (coin <= a) {
                    dp[a] = Math.min(dp[a], dp[a - coin] + 1); // this coin paid last
                }
            }
        }
        return dp[amount] == impossible ? -1 : dp[amount];
    }

    private static void show(int[] coins, int amount) {
        System.out.println("coins = " + Arrays.toString(coins) + ", amount = " + amount
                + " -> " + coinChange(coins, amount));
    }

    public static void main(String[] args) {
        show(new int[] {1, 2, 5}, 11);
        show(new int[] {2}, 3);
        show(new int[] {1}, 0);
        show(new int[] {1, 3, 4}, 6);
        show(new int[] {3, 7}, 11);
        show(new int[] {2, 5, 10, 1}, 27);
    }
}

Running it prints:

Output
coins = [1, 2, 5], amount = 11 -> 3
coins = [2], amount = 3 -> -1
coins = [1], amount = 0 -> 0
coins = [1, 3, 4], amount = 6 -> 2
coins = [3, 7], amount = 11 -> -1
coins = [2, 5, 10, 1], amount = 27 -> 4

Look at the fourth line: coins 1, 3 and 4 pay 6 with 2 coins, the 3 + 3 that reaching for the biggest coin missed. Example 3, on the third line, gives 0 straight from dp[0], because the loop over amounts never runs.

The fifth line prints -1 even though both coins, 3 and 7, are smaller than 11. Threes alone reach 9 or 12, and 7 plus threes reaches 10 or 13, so dp[11] keeps its impossible value. On the last line, 4 is 10 + 10 + 5 + 2.

Why amount + 1 and not Integer.MAX_VALUE, the largest int? With Integer.MAX_VALUE as the start value, Example 2 goes wrong. The entry dp[1] keeps that value, and adding 1 to it for amount 3 wraps around to -2,147,483,648, the smallest int. That number wins Math.min, and the method returns -2147483648 instead of -1.

The original implementation, CoinChange.java, is on GitHub.

Complexity

The work is the two loops over the dp array: one step for every pair of an amount and a coin.

  • Time: O(amount × c) for c coin values, because each amount from 1 to amount tries every one of the c coins with one subtraction and one Math.min.
  • Space: O(amount), because dp keeps one entry for each amount from 0 to amount and nothing else grows with the input.

Perfect Squares uses the same last-coin idea, with the square numbers 1, 4, 9 and so on as the coins.