Problem overview
CoinChange receives an int[] of coin values and an int named amount. It returns the fewest coins that add up to exactly amount, or -1 when no combination works. Every coin value may be used any number of times.
With coins {1, 2, 5} and amount 11 the answer is 3 (5 + 5 + 1). With {2} and amount 3 it is -1, since 2s only make even sums. With {1, 3, 4} and amount 6 it is 2 (3 + 3). Amount 0 needs no coins, so it returns 0.
Approach: the best answer for every smaller sum
Always taking the largest coin that fits looks tempting but is wrong: for {1, 3, 4} and 6 it picks 4 + 1 + 1, three coins, while 3 + 3 uses two. Trying every combination is far too slow, because coins can repeat.
Instead, let dp[i] be the fewest coins that make the sum i. If the last coin added is coin, the coins before it make i - coin, so dp[i] is dp[i - coin] + 1. Trying every coin as the last one and keeping the smallest gives dp[i]. Every entry reuses answers for smaller sums, so filling the table from 1 up to amount works.
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. A value of amount + 1 can therefore never be a real answer, and it works as "impossible so far". It also behaves well in the formula: when i - coin can't be made, dp[i - coin] + 1 is above amount too, and it never beats a real answer.
A plain recursion that tries every coin from every remaining sum would solve the same sums again and again, and its running time grows exponentially with the amount. The table solves each sum exactly once, which is what turns the problem into a pair of nested loops.
Step by step
- Create
dpwithamount + 1entries, indexes 0 toamount, and fill every entry withamount + 1usingArray.Fill. A newintarray holds zeros, so the fill is needed. - Set
dp[0] = 0. The sum 0 takes no coins, and every other sum is built on it. - Loop
ifrom 1 toamountinclusive. By the time the loop reachesi, all smaller sums are done. - Loop over the coins with
foreach. Each coin is tried as the last one added. - Check
coin <= i. A bigger coin doesn't fit, andi - coinwould be a negative index. - Update
dp[i]toMath.Min(dp[i], dp[i - coin] + 1). - If
dp[amount] > amount, return -1. Only a sum that no combination makes keeps its starting value. - Otherwise return
dp[amount].
For coins {1, 3, 4} and amount 6, the table ends as:
dp = 0 1 2 1 1 2 2
Here dp[6] is 2. For coins {2} and amount 3 the table ends as 0 4 1 4: the sum 3 still holds its marker 4, which is more than 3, so the method returns -1.
Walking through coins 1, 2, 5 and amount 11
For coins {1, 2, 5} and amount 11 the finished table is:
dp = 0 1 1 2 2 1 2 2 3 3 2 3
Entry 11 is the minimum of three candidates, one per coin. Coin 1 gives dp[10] + 1 = 3, coin 2 gives dp[9] + 1 = 4, and coin 5 gives dp[6] + 1 = 3. The smallest is 3, which matches 5 + 5 + 1. Notice that the table never records which coins were used, only how many. That is all the problem asks for.
The solution in C#
class Solution {
public int CoinChange(int[] coins, int amount) {
int[] dp = new int[amount + 1];
Array.Fill(dp, amount + 1);
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
foreach (int coin in coins) {
if (coin <= i) {
dp[i] = Math.Min(dp[i], dp[i - coin] + 1);
}
}
}
if (dp[amount] > amount) return -1;
return dp[amount];
}
}
Details worth knowing:
Array.Fill.Array.Fill(dp, value)sets every element of an array to one value. It is inSystem.- Why not
int.MaxValueas the marker?dp[i - coin] + 1would then overflow and wrap to a large negative number, whichMath.Minwould pick as the "best" answer. The markeramount + 1is small enough to add 1 to safely. - Large coin values. A coin can be as large as
int.MaxValue. The checkcoin <= ikeeps it out of the formula, so with coins{2147483647}and amount 10000 the method returns -1 without any problem. foreachover an array reads each element in order; the loop variablecoincan't be assigned to.
Complexity
Let n be the number of coins.
Time: O(n · amount). The outer loop runs amount times and the inner one n times, with constant work inside.
Space: O(amount) for the dp table.
Edge cases and common mistakes
- Amount 0. The loops don't run, and the method returns
dp[0], which is 0, for any coins. - Coins bigger than the amount.
{5, 10}with amount 3 returns -1. - Forgetting the
coin <= icheck. It leads to a negative index and anIndexOutOfRangeException. - Returning
dp[amount]unconditionally. An impossible amount would returnamount + 1instead of -1. - Greedy choice. Taking the largest coin first fails for
{1, 3, 4}and 6. - Leaving the table at zeros. Every sum would look makeable with 0 coins, and the answers would all be 0.
Testing
- Coins
{1, 2, 5}, amount 11 gives3. - Coins
{2}, amount 3 gives-1. - Coins
{1, 3, 4}, amount 6 gives2. - Coins
{1}, amount 0 gives0. - Coins
{5, 10}, amount 3 gives-1. - Coins
{186, 419, 83, 408}, amount 6249 gives20.
