Online store~25 min2s · 256 MBtarget O(amount × n) time, O(amount) spaceclassic twin: lc-322knapsack
An online store pays small refunds in coins at a pickup counter. The counter holds coins of a few fixed values and has as many coins of each value as it needs.
For each refund, the counter wants to hand out as few coins as possible, so that the customer carries less and the till is emptied less often.
Write fewest_coins(amount, coins).
amount is the refund, a whole number of units.coins lists the coin values. Each value can be used any number of times.amount, or -1 when no combination of coins does.Input: amount = 10, coins = [1, 5, 6, 8]
Output: 2Let best[a] be the fewest coins that pay a. Paying 0 takes 0 coins. To pay a, try each coin that fits as the last coin, and take the smallest best[a - coin] + 1. Fill the amounts upwards.
| amount | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|
| best | 0 | 1 | 2 | 3 | 4 | 1 | 1 | 2 | 1 | 2 | 2 |
The last cell holds 2: two coins of 5. The largest coin first would hand out 8, 1 and 1, which is 3 coins.
Input: amount = 3, coins = [2]
Output: -1Coins of 2 can never add up to an odd amount.
Input: amount = 6, coins = [1, 3, 4]
Output: 2Two coins of 3 pay 6. The largest coin first would use 4, 1 and 1.
1 ≤ amount ≤ 100001 ≤ len(coins) ≤ 100, and every value is between 1 and 10000There are 10,000 amounts and up to 100 coins, so a table with one entry for each amount costs about a million small steps. Trying every sequence of coins is far too slow, because the number of sequences grows exponentially with the amount.