Algorithms · Level 3 Dynamic Programming

Coin Change

Give change with the fewest coins by building the answer for every amount from zero up, where always taking the biggest coin goes wrong.

  • a table for every amount up to the target
  • best[a] = 1 + min(best[a - coin])
  • the biggest coin first is not always best

Build an answer for every amount from 0 up: the fewest coins for a is 1 plus the best for a - coin, over every coin. Trap: always taking the biggest coin fails; with coins 1, 3 and 4, it pays 6 as 4 + 1 + 1.

# fewest moves from 0 to n, each +1 or ×2
best = [0] * 11
for n in range(1, 11):
    best[n] = best[n - 1] + 1
    if n % 2 == 0:
        best[n] = min(best[n], best[n // 2] + 1)
best[10]  # 5: 0 → 1 → 2 → 4 → 5 → 10

Write fewest_coins(coins, amount): the fewest coins that add up to amount (each coin can be used many times), or -1 if it can't be paid. Example: fewest_coins([1, 3, 4], 6) → 2.

solution.py
Test Suites Pending
Output