PythiloLesson 28 of 32 · progress kept in this browser

Fill a table for the fewest coins

Greedy change fails for coins 1, 3 and 4 with amount 6: taking 4 first needs three coins, while 3 + 3 needs two. Dynamic programming tries every last coin for every smaller amount.

coins = [1, 3, 4]
# fewest coins for amounts 0..4
best = [0, 1, 2, 1, 1]
Your task

Write fewest_coins(coins, amount) returning the minimum number of coins summing to amount, with unlimited coins of each value, or -1 if impossible.