Change with the fewest coins
A vending machine gives change in unusual denominations and wants to use as few coins as possible. Greedy fails here – dynamic programming is needed.
The office coffee machine has coins of a few denominations (as many of each as needed) and has to give change amount using the fewest coins. The denominations can be unusual (tokens, local currencies), so we cannot assume that "take the largest coin that fits" always works.
Task
The function gets a list of distinct positive denominations coins and an amount amount ≥ 0. Return the minimum number of coins that add up exactly to amount, or -1 when it cannot be done. For amount = 0 the result is 0.
Signatures: minCoins(coins, amount) (JS/TS), min_coins(coins, amount) (Python), Solution.MinCoins (C#), Solution.minCoins (Java), MinCoins (Go).
Examples
coins | amount | Result | Notes |
|---|---|---|---|
[1, 2, 5] | 11 | 3 | 5 + 5 + 1 |
[1, 3, 4] | 6 | 2 | 3 + 3 – greedy would give 4 + 1 + 1 |
[2] | 3 | -1 | |
[5, 10, 25] | 0 | 0 |
Constraints
1 ≤ coins.length ≤ 12,1 ≤ coins[i] ≤ 10,000,0 ≤ amount ≤ 10,000.
Expected complexity
O(amount · k) time for k denominations, O(amount) memory.