0:00 / 0:00

The fewest coins that add up to an amount. Greedy fails, so build up from zero, reusing the best answer for each smaller amount.

▼

The problem

LeetCode 322 (Medium). Given coin denominations and an amount, return the fewest coins that add up to the amount, or -1 if no combination makes it. Each coin can be used any number of times.

Example: coins [1, 3, 4], amount 6 → 2 (3 + 3).

from math import inf

def coin_change(coins, amount):
    dp = [0] + [inf] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a:
                dp[a] = min(dp[a], dp[a - c] + 1)
    return dp[amount] if dp[amount] < inf else -1
TRY IT ON LEETCODE ▶

The solution

from math import inf

def coin_change(coins, amount):
    dp = [0] + [inf] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a:
                dp[a] = min(dp[a], dp[a - c] + 1)
    return dp[amount] if dp[amount] < inf else -1

Transcript

Coin Change. You get some coin values and an amount. Return the fewest coins that add up to the amount, or minus one if no mix can make it. Each coin can be reused.

Say the coins are one, three and four, and the amount is six. The obvious move is greedy: grab the biggest coin that fits. Four, then one, then one. Three coins. But three plus three makes six with just two. Biggest first can paint you into a corner.

So try everything. Take any coin, then solve what's left the same way. Six branches into five, three and two, and each of those branches again. For six, that's twenty-four calls. For thirty, over two and a half million. And the same small amounts keep coming back: amount one alone gets solved six times.

Instead, solve each amount once, starting from zero. Line up a jar for every amount, zero to six. Jar zero needs no coins. To fill any other jar, try each coin that fits: that coin, plus the best count for what's left, which already sits in a smaller jar. Keep the smallest.

Let's fill them. Jar one: a single one. Jar two: one plus one. Jars three and four take one coin each. Jar five: a four plus a one. Now jar six. A one coin plus jar five makes three. A three coin plus jar three makes two. A four coin plus jar two makes three. Best is two: three plus three.

In code, the table starts with zero, then infinity everywhere else. For each amount, and each coin that fits, keep the smaller of the current entry and the entry for amount minus coin, plus one. If the last entry is still infinity, no mix works, so return minus one.

Every amount tries every coin, so the time is amount times coins. For thirty, that's ninety checks, not millions of calls. The space is one jar per amount.

Small amounts first, then build up. That's Coin Change.