Skip to content
BytePatterns

Coin Change

Dynamic Programming: lesson 5 of 20

Fewest pieces to hit a target, one amount at a time.

Lesson 5 of 20 · 6 min

Coin Change

Step 1 of 13

best[a] is the fewest coins that make exactly a. Start with best[0] = 0 and every other amount at ∞.

The Idea

Build the answer for every amount from 1 up to the target. The fewest pieces making amount a is one more than the fewest making a minus some coin, so try each coin and keep the smallest result. Amounts nothing can reach stay at infinity, which is exactly how the function knows to report failure.

Real-World Example

A banquet hall seating a party of 46 from tables of four, six, and ten. Fewer tables means more dance floor, so the manager works upward from small parties: once the answer for 36 is on the sheet, adding one ten-seater settles 46 immediately.

The Code

def fewest(coins, target):
    INF = float("inf")
    best = [0] + [INF] * target              # best[a] = fewest coins making a
    for a in range(1, target + 1):
        for c in coins:
            if c <= a and best[a - c] + 1 < best[a]:
                best[a] = best[a - c] + 1    # one coin on top of a solved amount
    return -1 if best[target] == INF else best[target]

print(fewest([1, 5, 10], 27))   # 5
print(fewest([4, 6], 7))        # -1

Python

Your turn

Put the steps in the right order.

  1. Walk the amounts from 1 up to the target
  2. Return best[target], or -1 if it never improved
  3. For each coin that fits, try best[amount - coin] + 1 as a better answer
  4. Set best[0] to 0 and every other amount to infinity

Mini quiz

1 / 3

In the table, best[a] means:

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.