The fewest coins that make 6 with coins 1, 3 and 4. Greedy says 4 + 1 + 1; dynamic programming finds 3 + 3.
Python · intermediate · 10 min · 67 steps · free
def min_coins(coins, amount):
best = [0] + [float('inf')] * amount
for total in range(1, amount + 1):
for coin in coins:
if coin <= total:
best[total] = min(best[total], best[total - coin] + 1)
return best[amount]
print(min_coins([1, 3, 4], 6))min_coins(). Its body does not run yet: it runs each time the function is called.min_coins(), with coins = [1, 3, 4] and amount = 6. It gets its own names.best[x] will hold the fewest coins for amount x. best[0] = 0; the rest start as infinity (not reachable yet).total is created with the value 1.coin is created with the value 1.coin <= total is true, so the block under it runs.coin changes from 1 to 3.coin <= total is false, so the block under it is skipped.coin changes from 3 to 4.coin <= total is false, so the block under it is skipped.for coin in coins.total changes from 1 to 2.coin changes from 4 to 1.coin <= total is true, so the block under it runs.best points to, index 2 changes from inf to 2.coin changes from 1 to 3.coin <= total is false, so the block under it is skipped.coin changes from 3 to 4.coin <= total is false, so the block under it is skipped.for coin in coins.total changes from 2 to 3.coin changes from 4 to 1.coin <= total is true, so the block under it runs.best points to, index 3 changes from inf to 3.coin changes from 1 to 3.coin <= total is true, so the block under it runs.coin changes from 3 to 4.coin <= total is false, so the block under it is skipped.for coin in coins.total changes from 3 to 4.coin changes from 4 to 1.coin <= total is true, so the block under it runs.best points to, index 4 changes from inf to 2.coin changes from 1 to 3.coin <= total is true, so the block under it runs.best[total] = min(best[total], best[total - coin] + 1).coin changes from 3 to 4.coin <= total is true, so the block under it runs.best points to, index 4 changes from 2 to 1.for coin in coins.total changes from 4 to 5.coin changes from 4 to 1.coin <= total is true, so the block under it runs.best points to, index 5 changes from inf to 2.coin changes from 1 to 3.coin <= total is true, so the block under it runs.best[total] = min(best[total], best[total - coin] + 1).coin changes from 3 to 4.coin <= total is true, so the block under it runs.best[total] = min(best[total], best[total - coin] + 1).for coin in coins.total changes from 5 to 6.coin changes from 4 to 1.coin <= total is true, so the block under it runs.coin changes from 1 to 3.coin <= total is true, so the block under it runs.coin changes from 3 to 4.coin <= total is true, so the block under it runs.best[total] = min(best[total], best[total - coin] + 1).for coin in coins.for total in range(1, amount + 1).min_coins() has finished, so its names are gone. It prints 2.Answer: O(A × C)
Answer: 0. No coins make 0.
← Dynamic Programming: Memo and Table