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 coinsamountamount
Example 1
Output: 3
Explanation: 5 + 5 + 1.
Example 2
Output: -1
Example 3
Output: 0
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.
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 dpdp[a]adp[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
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
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]dp[0]
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 + 1impossibledp[amount]
Java Solution
The method coinChange
- First, set
toimpossible . Create the arrayamount + 1 with one entry for each amount from 0 todp , fill it withamount usingimpossible , and then setArrays.fill to 0.dp[0] - A loop moves
from 1 up toa . Inside it, a second loop takes eachamount fromcoin in turn.coins - For a coin no bigger than
,a is the number of coins when that coin is paid last. The calldp[a - coin] + 1 keeps the smaller of that count and the currentMath.min .dp[a] - When both loops are done, return -1 if
still equalsdp[amount] , andimpossible otherwise.dp[amount]
A small helper, showmain
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:
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]
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]impossible
Why amount + 1Integer.MAX_VALUEintInteger.MAX_VALUEdp[1]intMath.min
The original implementation,
Complexity
The work is the two loops over the dp
- Time: O(amount × c) for c coin values, because each amount from 1 to
tries every one of the c coins with one subtraction and oneamount .Math.min - Space: O(amount), because
keeps one entry for each amount from 0 todp and nothing else grows with the input.amount