How do you find the minimum number of coins that make a given amount?
Build a table where each entry is the fewest coins needed for that amount. For every amount from one upwards, try each coin as the last coin used and take the smallest result.
def coin_change(coins, amount):
table = [0] + [float('inf')] * amount
for value in range(1, amount + 1):
for coin in coins:
if coin <= value and table[value - coin] + 1 < table[value]:
table[value] = table[value - coin] + 1
return -1 if table[amount] == float('inf') else table[amount]
print(coin_change([1, 2, 5], 11))
print(coin_change([2], 3))The outputs are 3 and minus one. Eleven can be made with three coins, for example five plus five plus one, and the amount three cannot be made at all from twos, so no solution exists.
The mechanism is the recurrence. Any solution for an amount ends with some coin, and removing that coin leaves a solution for a smaller amount, so the minimum is one plus the minimum over the smaller amounts. Filling the table in increasing order of amount guarantees that every smaller amount is already solved.
The trade-off to name is that the table is linear in the amount, which is fine for a few thousand but becomes the bottleneck for very large amounts. The bottom up version also allows unlimited copies of each coin, whereas the version where each coin may be used once needs the coins in the outer loop, and swapping the two loops is exactly the difference between combinations and permutations. It is worth saying which convention you are using, because the loop order silently decides it.