
Dynamic Programming
Time to fix the greedy cashier from Greedy or Not? with a DP table. DP checks every option, but it never solves the same small problem twice. So it is always correct, and still fast.
Fewest coins
Let best[a] be the fewest coins that make amount a.
best[0] = 0, because making 0 needs no coins.- For a bigger amount
a, try each coin as the last coin. If the last coin isc, you needbest[a - c]coins for the rest, plus 1.
best[a] = smallest (best[a - c] + 1) for each coin c <= a
Here is the whole table for coins [1, 3, 4]:
| amount | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| best | 0 | 1 | 2 | 1 | 1 | 2 | 2 |
For amount 6, the last coin could be:
- 1:
best[5] + 1 = 3coins - 3:
best[3] + 1 = 2coins - 4:
best[2] + 1 = 3coins
The smallest is 2 (that's 3 + 3). Greedy said 3!
Some amounts can't be made at all. They start as "infinity", which
Python writes as float("inf"). Every number is smaller than it.
This takes O(amount × number of coins) steps, which is fast.
Assignment
Write min_coins(coins, amount). Coins can be used again and again.
- The table starts as
best = [0] + [INF] * amount. - For each amount
afrom 1 toamount, try every coincwithc <= a. Keep the smallestbest[a - c] + 1inbest[a]. - Return
best[amount], or-1if it is stillINF(impossible).
min_coins([1, 3, 4], 6) is 2.
Write min_coins(coins, amount). Coins can be used again and again.
- The table starts as
best = [0] + [INF] * amount. - For each amount
afrom 1 toamount, try every coincwithc <= a. Keep the smallestbest[a - c] + 1inbest[a]. - Return
best[amount], or-1if it is stillINF(impossible).
min_coins([1, 3, 4], 6) is 2.
Press Run to try your code, then Check to test it.