8/28
Part 2 of 7 · Spot the dynamic programLearn and do
Fewest coins: fill a table from 0 up
Each cell looks back one coin
Fill the table from 0 up, so every is ready before needs it:
import math
def min_coins(amount: float, coins: list[float]) -> int:
"""The fewest coins that make amount exactly, or -1."""
target = round(amount * 100)
values = sorted({round(c * 100) for c in coins})
# best[t]: fewest coins for t cents
best = [0] + [math.inf] * target
for t in range(1, target + 1):
for v in values:
if v <= t and best[t - v] + 1 < best[t]:
best[t] = best[t - v] + 1
return -1 if best[target] == math.inf else best[target]
print(min_coins(0.06, [0.01, 0.03, 0.04]))
print(min_coins(1.15, [0.05]))
print(min_coins(0.03, [0.02, 0.05]))
What do the three calls give: 6 cents from 1, 3, 4, then $1.15 from nickels, then 3 cents from 2 and 5?
Pick one to see what it prints.
Pick an answer above to see the rest