Code

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 is c, you need best[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 = 3 coins
  • 3: best[3] + 1 = 2 coins
  • 4: best[2] + 1 = 3 coins

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.

  1. The table starts as best = [0] + [INF] * amount.
  2. For each amount a from 1 to amount, try every coin c with c <= a. Keep the smallest best[a - c] + 1 in best[a].
  3. Return best[amount], or -1 if it is still INF (impossible).

min_coins([1, 3, 4], 6) is 2.