Problem overview
The function coinChange receives an IntArray of coin values, coins, and an amount. It returns the fewest coins that add up to exactly amount, or -1 when no combination works. Each coin value can be used any number of times. An amount of 0 needs no coins, so the answer is 0.
With coins = [1, 2, 5] and amount = 11 the answer is 3: 5 + 5 + 1. Two coins can't do it, since the largest sum of two coins is 10. With coins = [2] and amount = 3 the answer is -1, because a coin of 2 only makes even sums.
Approach: the fewest coins for every smaller sum
Greedy thinking, always taking the largest coin that fits, is tempting and wrong. For coins = [1, 3, 4] and amount = 6 it picks 4 + 1 + 1, three coins, while 3 + 3 uses two. Trying every combination of coins is correct but its running time grows exponentially.
The dynamic programming idea is to answer the question for every sum from 0 up to amount. Let dp[i] be the fewest coins that make the sum i. To make i, some coin is the last one added. If that coin is coin, the coins before it make i - coin, which is a smaller sum whose answer is already in the table. So the candidate is dp[i - coin] + 1. Trying every coin and keeping the smallest candidate gives dp[i].
The table starts at amount + 1 in every entry. Every coin is worth at least 1, so no sum i ever needs more than i coins, and a count of amount + 1 can't be a real answer. It works as "not reachable yet", and it is large enough that minOf always replaces it with a real count when one exists. A sum that nothing can make keeps this marker, which is how the function knows to return -1.
For coins = [1, 3, 4] and amount = 6 the finished table is:
coins=[1, 3, 4] amount=6 dp=[0, 1, 2, 1, 1, 2, 2]
Entry 6 is 2, from dp[3] + 1. For coins = [2] and amount = 3 the table is:
coins=[2] amount=3 dp=[0, 4, 1, 4]
Here the marker is 4. Entries 1 and 3 never improved, and dp[3] is greater than amount, so the answer is -1.
Step by step
- Create
dpasIntArray(amount + 1) { amount + 1 }. There areamount + 1entries, for the sums 0 toamount, and each starts at the marker. - Set
dp[0]to 0. The sum 0 takes no coins, and every other entry is built on top of it. - Loop
iover1..amount. Each entry needs only smaller sums, which are finished by the time the loop reachesi. Whenamountis 0 the range is empty. - Loop over
coins, treating eachcoinas the last one added to makei. - Check
coin <= i. A coin larger thanidoesn't fit, andi - coinwould be a negative index. - Update
dp[i]withminOf(dp[i], dp[i - coin] + 1). - Return
-1ifdp[amount]is still greater thanamount. - Otherwise return
dp[amount].
The solution in Kotlin
class Solution {
fun coinChange(coins: IntArray, amount: Int): Int {
val dp = IntArray(amount + 1) { amount + 1 }
dp[0] = 0
for (i in 1..amount) {
for (coin in coins) {
if (coin <= i) {
dp[i] = minOf(dp[i], dp[i - coin] + 1)
}
}
}
if (dp[amount] > amount) return -1
return dp[amount]
}
}
The Kotlin details worth a look:
IntArray(size) { init }. The lambda runs once per index and returns that entry's starting value. Here it ignores the index and returnsamount + 1.IntArray(size)alone would fill the array with zeros, which would wrongly say every sum needs no coins.1..amountincludes both ends. The sumamountitself is computed. Whenamountis 0,1..0is empty, the loops are skipped, and the function returnsdp[0], which is 0.for (coin in coins)iterates over the values of anIntArraydirectly, with no index needed.minOfis in the standard library, so it needs no import.dp[i]is anIntelement of an array, assigned with the ordinary=.- Guarding
i - coin. Without theif, a coin larger thanigives a negative index, and the array access throws anArrayIndexOutOfBoundsException. This also matters for coin values as large as2147483647: the checkcoin <= iis false, so the subtraction never runs. - No
Intoverflow. The largest value stored is the marker plus one, at most 10,002, far from the 32-bit limit. - The early
returnon one line.if (dp[amount] > amount) return -1needs no braces. Kotlin'sifalso works as an expression, but here it is used as a statement.
Complexity
Let n be the number of coins.
Time: O(n * amount). The outer loop runs amount times and the inner loop runs n times for each, with constant work inside.
Space: O(amount). The table has amount + 1 entries, and nothing else grows.
Edge cases and common mistakes
- Amount 0.
coins = [1]withamount = 0returns 0. - Impossible amounts.
coins = [5, 10]withamount = 3returns-1, and so doescoins = [2147483647]withamount = 10000. - Greedy choice. The largest-coin-first shortcut gives 3 coins for
[1, 3, 4]and 6 where the table finds 2. - Starting the table at 0. Then
minOfkeeps 0 for every entry and the function reports that no coins are needed. - Starting the table at
Int.MAX_VALUE. Thendp[i - coin] + 1overflows and wraps toInt.MIN_VALUEfor an unreachable sum, which looks like the smallest count of all. The markeramount + 1avoids this. - Forgetting
-1. Returningdp[amount]directly would giveamount + 1for impossible inputs, such as 4 for[2]and 3. - Walking down from
amount. The table must be filled from small sums up, so thatdp[i - coin]is final when it is read.
Testing
These inputs give the following results from the reference solution:
coins = [1, 2, 5],amount = 11gives3.coins = [2],amount = 3gives-1.coins = [1, 3, 4],amount = 6gives2.coins = [1],amount = 0gives0.coins = [5, 10],amount = 3gives-1.coins = [7],amount = 14gives2.coins = [186, 419, 83, 408],amount = 6249gives20.
