Python coding

Fewest coins for an amount

You have an unlimited supply of coins of each value in coins. Return the smallest number of coins that add up to exactly amount, or -1 if no combination does.

Coin values are positive integers, possibly unsorted or repeated; amount is at least 0, and an amount of 0 needs no coins.

Besides the tests, one large input (an amount of 32) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • fewest_coins([1,4,6], 8) → 2
  • fewest_coins([2,5], 11) → 4
  • fewest_coins([3], 7) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Largest coin first fails: with [1, 4, 6] and 8 it takes 6 + 1 + 1, but 4 + 4 is better. Build from smaller amounts instead.

Hint 2

best[a] = 1 + min(best[a - c]) over coins c ≤ a, with best[0] = 0. Fill a upward; an amount nothing reaches stays at infinity, which means -1.

Solution and why it works
pythonO(amount · len(coins)) · O(amount)
def fewest_coins(coins: list[int], amount: int) -> int:
    INF = amount + 1                     # no real answer uses more than `amount` coins
    best = [0] + [INF] * amount          # best[a] = fewest coins that sum to a
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and best[a - c] + 1 < best[a]:
                best[a] = best[a - c] + 1    # last coin c on top of the best pile for a - c
    return best[amount] if best[amount] < INF else -1

The last coin of an optimal pile for a is some c, and the rest must be an optimal pile for a − c, so best[a] needs only smaller amounts: amount × coins steps of O(1) work. amount + 1 works as infinity because coins are at least 1. The trap is greedy: largest-first uses 3 coins for 8 with [1, 4, 6], and gives up on 11 with [2, 5], where 5 + 2 + 2 + 2 works.

Related lab: Big-O growth