Problem overview
The method coinChange receives an int[] of coin values and an int amount. It returns the fewest coins that add up to exactly amount, or -1 when no combination works. Each coin value can be used as many times as you like. When amount is 0, the answer is 0.
For coins = [1, 2, 5] and amount = 11 the answer is 3, from 5 + 5 + 1. For coins = [2] and amount = 3 it is -1, because 2s only make even sums.
Approach: the fewest coins for every sum up to amount
A tempting shortcut is to always take the largest coin that still fits. It fails for coins = [1, 3, 4] and amount = 6: greedy takes 4 + 1 + 1, three coins, but 3 + 3 uses two. Trying every combination is correct but far too slow, so we solve smaller versions of the problem and reuse them.
Let dp[i] be the fewest coins that make the sum i. Suppose the last coin added was coin. Then the coins before it make the sum i - coin, using dp[i - coin] coins, so the total is dp[i - coin] + 1. We don't know which coin comes last, so we try every coin and keep the smallest result. Each entry depends only on smaller sums, so filling the table from 1 up to amount always finds the needed entries ready.
Sums that can't be made need a marker. Every coin is worth at least 1, so no sum i ever needs more than i coins, and amount + 1 can never be a real answer. We start every entry at amount + 1 to mean "not reachable yet". An unreachable dp[i - coin] plus 1 still exceeds amount, so it never beats a real answer.
The table for coins = [1, 2, 5] and amount = 11, entries 0 to 11, is:
[0, 1, 1, 2, 2, 1, 2, 2, 3, 3, 2, 3]
The last entry is 3, the answer. For coins = [1, 3, 4] and amount = 6 it is [0, 1, 2, 1, 1, 2, 2], so dp[6] is 2. For coins = [2] and amount = 3 it is [0, 4, 1, 4]: the 4s are the "unreachable" marker, and dp[3] = 4 is above 3, so the answer is -1.
The table keeps the minimum over several choices, rather than a sum of counts. The coins may come in any order and may repeat, so the table never has to remember which coins were used, only how many. That is what makes it small: amount + 1 numbers describe every sub-problem.
Step by step
- Create
dp, anintarray of sizeamount + 1so that indexamountexists, and fill it withamount + 1usingArrays.fill. A new int array starts with zeros, which would claim every sum takes no coins. - Set
dp[0] = 0. The sum 0 needs no coins, and every other sum is built on top of it. - Loop
ifrom 1 toamountinclusive, smallest sum first. - Loop over the coins with an enhanced
for. Each coin is tried as the last one added to makei. - Check
coin <= i. A coin worth more thanidoesn't fit, andi - coinwould be a negative index. - Update
dp[i]to the smaller of its current value anddp[i - coin] + 1, usingMath.min. - After the loops, test
dp[amount] > amountand return -1: the sum was never reached. - Otherwise return
dp[amount].
The solution in Java
class Solution {
public int coinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Arrays.fill(dp, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int coin : coins) {
if (coin <= i) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
if (dp[amount] > amount) return -1;
return dp[amount];
}
}
Java details worth noticing:
Arrays.fillcomes fromjava.util.Arraysand sets every entry of an array to one value. Outside the lesson's editor you needimport java.util.Arrays;at the top of the file.- The enhanced
forloop.for (int coin : coins)visits each element by value, and no index is needed because only the coin values matter. - One-line
if.if (dp[amount] > amount) return -1;works without braces. Braces are still safer when you later add a second statement. - No overflow. The marker is at most
amount + 1, about 10,001, and the+ 1never gets near theintlimit. Coin values as large as 2^31 - 1 are fine too, sincecoin <= ikeeps them out of the arithmetic unless they fit withinamount.
Complexity
Time: O(n · amount), where n is the number of coins. The outer loop runs amount times, the inner one n times, and each pass does constant work.
Space: O(amount) for the table of amount + 1 integers.
Edge cases and common mistakes
amount = 0. The loops don't run, and the method returnsdp[0], which is 0. Forcoins = [5]andamount = 0it returns 0, not -1.- Impossible amounts. For
coins = [3, 7]andamount = 5it returns -1, since no combination of 3s and 7s makes 5. - Greedy choice. Taking the biggest coin first gives 3 coins for
[1, 3, 4]and 6, while the answer is 2. - Forgetting the marker. Leaving the array at zeros makes every sum look free, and
Math.minwould always pick 0. - Using
Integer.MAX_VALUEas the marker without care.dp[i - coin] + 1then overflows to a large negative number and wins every comparison. That is why this solution usesamount + 1. - Skipping the
coin <= icheck. It leads to anArrayIndexOutOfBoundsExceptionas soon as a coin is larger than the current sum.
Testing
coins = [1, 2, 5],amount = 11gives3.coins = [2],amount = 3gives-1.coins = [1, 3, 4],amount = 6gives2.coins = [5],amount = 0gives0.coins = [3, 7],amount = 5gives-1.
