Problem overview
The method coinChange receives an array coins of coin values and an integer amount. It returns the fewest coins that add up to exactly amount, or -1 when no combination does. Each coin value can be used any number of times. There are up to 12 coin values, and amount is between 0 and 10,000. For amount = 0 the answer is 0, because no coins are needed.
With coins = [1, 2, 5] and amount = 11 the answer is 3, from 5 + 5 + 1. With coins = [2] and amount = 3 the answer is -1, since 2s only make even sums. With coins = [1, 3, 4] and amount = 6 the answer is 2, from 3 + 3.
Approach: the fewest coins for every sum up to amount
A tempting shortcut is to always take the largest coin that still fits. On [1, 3, 4] and 6 it takes 4, then 1, then 1: three coins, while 3 + 3 uses two. Greedy choices can be wrong here. Trying every combination is correct but takes exponential time.
Dynamic programming solves smaller versions of the question and reuses the answers. 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 that sum needs dp[i - coin] + 1 coins. Trying every coin as the last one and keeping the smallest result gives dp[i]. Fill the table from 1 up to amount, and every entry only needs smaller sums that are already done.
Two details need a choice of starting values:
dp[0]is 0: the sum 0 takes no coins.- Every other entry starts at
amount + 1. Each coin is worth at least 1, so no sumineeds more thanicoins, andamount + 1can never be a real answer. It works as "not reachable yet", and it is a finite number, so themincomparisons need no special case.
For coins = [1, 3, 4] and amount = 6, running the code gives these values:
| Sum i | dp[i] |
|---|---|
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
| 3 | 1 |
| 4 | 1 |
| 5 | 2 |
| 6 | 2 |
The answer is dp[6], which is 2. For coins = [2] and amount = 3, the final table is [0, 4, 1, 4]: sums 1 and 3 keep the starting value 4, which is more than the amount, so the method returns -1.
Step by step
- Create
dpas avararray ofInt. It hasamount + 1entries, all equal toamount + 1, built with[Int](repeating: amount + 1, count: amount + 1). It is avarbecause the loops write into it. - Set
dp[0]to 0. Every other sum is built on top of this one. - Loop over the sums with
iin1..<amount + 1, smallest first. Write the closing brace right away. - Loop over the coins with
coin, trying each as the last coin for the sumi. Write that closing brace too. - Check that the coin fits with
coin <= i. A coin worth more thaniwould makei - coinnegative, which is not a valid index. - Update the entry:
dp[i] = min(dp[i], dp[i - coin] + 1). It keeps the best result over all coins. - Return -1 when the target stayed unreachable. If
dp[amount]is still more thanamount, nothing made it. Swift needs the braces around theifbody, so it fits on one line as{ return -1 }. - Otherwise return
dp[amount].
The solution in Swift
class Solution {
func coinChange(_ coins: [Int], _ amount: Int) -> Int {
var dp = [Int](repeating: amount + 1, count: amount + 1)
dp[0] = 0
for i in 1..<amount + 1 {
for coin in coins {
if coin <= i {
dp[i] = min(dp[i], dp[i - coin] + 1)
}
}
}
if dp[amount] > amount { return -1 }
return dp[amount]
}
}
The Swift details worth a closer look:
- Range precedence.
1..<amount + 1needs no parentheses: the+is evaluated before the range operator, so the range is1..<(amount + 1). - Why half-open. When
amountis 0 the range is1..<1, which is empty, so the loops are skipped and the method returnsdp[0], which is 0. The closed range1...amountwould be1...0. A range can't end below its start, so that stops the program with a run-time error. [Int](repeating:count:). It builds an array with one value repeated. The array is a value type, so assigning intodpchanges onlydp.- Coins as large as 2^31 - 1. An
Intholds them without trouble, and thecoin <= icheck keeps them from being used as an index. Forcoins = [2147483647]andamount = 10000the method returns-1. - Overflow can't happen. The largest value ever added is
amount + 1plus 1, far below the limit of a 64-bitInt, which is why the "unreachable" marker is a plain number and notInt.max. WithInt.max, adding 1 would crash, because Swift traps on overflow. - Parameter labels. Both parameters are declared with
_, so the call iscoinChange([1, 2, 5], 11)without labels.
Complexity
Let n be the number of coin values.
Time: O(n · amount). The outer loop runs amount times, the inner loop runs n times for each, and each step is constant work.
Space: O(amount). The dp array has amount + 1 entries.
Edge cases and common mistakes
- Amount 0. Both
[1]and[2]with amount 0 return 0. - Unreachable amount.
[5, 10]with amount 3 returns-1, because both coins are larger than 3. - Coins larger than the amount. The
coin <= itest skips them, so the indexi - coinnever goes negative. - Greedy by largest coin. It fails on
[1, 3, 4]with 6, as shown above. - Starting the table at 0. If every entry began at 0,
minwould never find anything better than 0, and every sum would look free. - Forgetting the
-1case. Without the final check, an unreachable amount would returnamount + 1. - Looping over sums in descending order. Entry
ineeds smaller entries already finished, so the loop must go upward.
Testing
Results from running 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 = [2, 5, 10, 1],amount = 27gives4.coins = [186, 419, 83, 408],amount = 6249gives20.
