You get a list coins of coin values and a target amount. You can use each coin value as many times as you like.
Return the smallest number of coins whose values add up to exactly amount. If no mix of coins reaches it, return −1. An amount of 0 needs no coins at all.
Example 1
Input: coins = [1, 3, 4], amount = 6 Output: 2 Why: 3 + 3; starting with 4 needs 4 + 1 + 1
2 more examples and the constraints
Example 2
Input: coins = [4], amount = 7 Output: -1 Why: multiples of 4 skip over 7
Example 3
Input: coins = [3, 8], amount = 0 Output: 0 Why: nothing to pay, so no coins
Constraints
- 1 ≤ length of coins ≤ 12
- 1 ≤ each coin ≤ 2,147,483,647 (2³¹ − 1)
- 0 ≤ amount ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Plain recursionO(kⁿ)
- Recursion with memoO(n·k)
- Bottom-up tableO(n·k)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for amount 10,000 and 12 coins | Verdict |
|---|---|---|---|
| Plain recursion | O(kⁿ) | Shows the recurrence; far too slow | |
| Recursion with memo | O(n·k) | Passes; deep call stack | |
| Bottom-up table | O(n·k) | Best; no recursion at all |
n = the amount, k = how many coin values there are.
Edge cases to test
- Amount 0. The answer is 0 coins, whatever the coins are.
- Impossible amount. coins [3, 5] and amount 7 must give −1, not a sentinel like 8.
- Greedy trap. coins [1, 3, 4] and amount 6: biggest-first gives 3 coins, the right answer is 2.
- Huge coins. A coin of 2,147,483,647 never fits an amount up to 10,000. Check c ≤ a before computing a − c, and never add to such a coin.
Common mistakes
- Picking the largest coin first; it fails as soon as the coin values are not like real-world money.
- Using the maximum int as "impossible" and then adding 1, which overflows in Java and C++.
- Forgetting to turn the "impossible" marker back into −1 before returning.
How to talk through it
- 1Clarify. Can a coin be used more than once? What should I return when the amount cannot be made? Can the amount be 0?
- 2Rule out greedy. Show coins [1, 3, 4] with amount 6: largest-first uses 3 coins, but 3 + 3 uses 2.
- 3State the recurrence. fewest(a) = 1 + the smallest fewest(a − c) over coins c that fit, with fewest(0) = 0. Say why plain recursion repeats work.
- 4Fill it bottom-up. A table from 0 to the amount, amount + 1 as "unreachable"; O(n·k) time and O(n) space.
- 5Test out loud. Run amount 0, an impossible amount, and the greedy trap before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?