Problem overview
The method coinChange receives an array of coin values, coins, and a target 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 often as you like, and an amount of 0 needs 0 coins.
With coins = [1, 2, 5] and amount = 11 the answer is 3: 5 + 5 + 1. With coins = [2] and amount = 3 the answer is -1, because coins of 2 only make even sums.
Approach: the fewest coins for every smaller sum
Always taking the largest coin that fits looks natural, but it fails. For coins = [1, 3, 4] and amount = 6 it picks 4 + 1 + 1, three coins, while 3 + 3 uses two. Trying every combination is too slow, so we solve the same question for every sum from 0 up to amount.
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 the best way to use that coin is dp(i - coin) + 1. Try each coin that fits and keep the smallest result. Because i - coin is always smaller than i, filling the table from small sums to large ones means every value we need is already there.
For sums we can't make we 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. The table starts filled with amount + 1, meaning "can't make this yet". If dp(amount) is still above amount at the end, no combination exists.
Step by step
- Create
dpwithArray.fill(amount + 1)(amount + 1):amount + 1entries, each equal toamount + 1. - Set
dp(0)to 0. The sum 0 takes no coins, and every other entry is built on top of it. - Loop
iover1 to amount. This fills the table from the smallest sum up. Whenamountis 0 the range is empty. - Loop over
coins. Each coin is tried as the last one added to makei. - Check
coin <= i. A coin worth more thanican't be part of the sum, andi - coinwould be a negative index. - Update
dp(i)tomath.min(dp(i), dp(i - coin) + 1). Ifi - coincan't be made,dp(i - coin) + 1is aboveamountas well, so it never looks like a real answer. - Return -1 if
dp(amount)is still aboveamount. Only a sum that nothing makes keeps its starting value. - Otherwise end with
dp(amount).
For coins = [1, 3, 4] and amount = 6, the finished table is:
0 1 2 1 1 2 2
The entry at index 6 is 2, which is 3 + 3. For coins = [2] and amount = 3 the table ends as 0 4 1 4: sum 2 is reachable with one coin, but sum 3 keeps its marker 4, which is above 3, so the method returns -1.
The solution in Scala
class Solution {
def coinChange(coins: Array[Int], amount: Int): Int = {
val dp = Array.fill(amount + 1)(amount + 1)
dp(0) = 0
for (i <- 1 to amount) {
for (coin <- coins) {
if (coin <= i) {
dp(i) = math.min(dp(i), dp(i - coin) + 1)
}
}
}
if (dp(amount) > amount) return -1
dp(amount)
}
}
The Scala details worth a closer look:
Array.fill(size)(value). It takes two parameter lists: the size first, then the value to repeat. The result is anArray[Int], which is mutable even though it is held in aval. Thevalkeeps the name pointing to the same array, anddp(i) = ...changes its contents.- Assignment with parentheses.
dp(0) = 0is how Scala writes an array element update, in the same style as readingdp(i). - Generators.
i <- 1 to amountrunsithrough the range includingamount, andcoin <- coinsruns through the array's elements. - Early
return.if (dp(amount) > amount) return -1leaves the method at once with the declaredIntresult. Without it, the last expression,dp(amount), is the normal result. - Large coin values. A coin can be as large as 2^31 - 1, the biggest
Int. The checkcoin <= icomes first, soi - coinis never computed for such a coin, andcoinChange(Array(2147483647), 5)returns -1 with no overflow.
Complexity
Time: O(n · amount), where n is the number of coins. The two nested loops make amount times n constant-time updates.
Space: O(amount). The table has amount + 1 entries.
Edge cases and common mistakes
- Amount 0. The loops don't run and the method returns
dp(0), which is 0, for any coins. - Impossible amounts.
coins = [5, 10]withamount = 3returns -1: no coin fits, sodp(3)keeps its starting value 4. - Greedy choice. Taking the largest coin first gives three coins for
[1, 3, 4]and 6, while the table finds two. - Forgetting the
coin <= icheck. For a coin larger thanithe indexi - coinis negative, and the program throws anArrayIndexOutOfBoundsException. - Using 0 as the "impossible" marker. Then
math.minwould always keep 0 and report that every sum needs no coins. The marker must be larger than any real answer. - Using
Int.MaxValueas the marker. Adding 1 to it wraps to a large negative number and corrupts the minimum.amount + 1is large enough and can't overflow.
Testing
coins = [1, 2, 5],amount = 11gives 3.coins = [2],amount = 3gives -1.coins = [1, 3, 4],amount = 6gives 2.coins = [2, 5, 10, 1],amount = 27gives 4.coins = [186, 419, 83, 408],amount = 6249gives 20.coins = [1],amount = 0gives 0.coins = [5, 10],amount = 3gives -1.
