Skip to content

Coin Change

MediumLeetCode #322Time O(amount × coins)Space O(amount)

You have coin denominations (each usable any number of times) and a target amount. Return the smallest number of coins that sum to the amount, or -1 if no combination works. An amount of 0 needs 0 coins.

coins = [1, 2, 5], amount = 11 -> 3 (5 + 5 + 1)
coins = [2], amount = 3 -> -1

Greedy (“always take the biggest coin”) is wrong: with [1, 3, 4] and amount 6 it picks 4 + 1 + 1 (three coins) but 3 + 3 uses two. Brute-force recursion works but recomputes the same amounts over and over.

The last coin you use is one of the denominations, and what is left is a smaller instance of the same problem. So define dp[a] as the fewest coins to make a: dp[a] = min(dp[a - coin] + 1) over every coin <= a, with dp[0] = 0. Fill a from 1 up to amount. Start every other cell at amount + 1 (an impossible “infinity”); if dp[amount] is still that, return -1.

Show solutionHide solution
def coin_change(coins: list[int], amount: int) -> int:
INF = amount + 1 # larger than any real answer
dp = [0] + [INF] * amount # dp[a] = fewest coins that make amount a
for a in range(1, amount + 1):
for coin in coins:
if coin <= a:
dp[a] = min(dp[a], dp[a - coin] + 1)
return dp[amount] if dp[amount] != INF else -1
  • Time: O(amount × coins) — each of the amount cells tries every coin once.
  • Space: O(amount) — one array of amount + 1 entries.
  • Don’t use greedy. It fails on [1, 3, 4], amount 6. Say why if asked.
  • Amount 0 returns 0, not -1. dp[0] = 0 handles it with no special case.
  • Pick a safe “infinity”. amount + 1 can never be a real answer (the worst case is amount coins of value 1), and adding 1 to it can’t overflow in Java. Avoid Integer.MAX_VALUE plus 1.
  • Unreachable is a normal result. Convert leftover infinity to -1 at the end.

Count the number of combinations that make the amount, not the fewest coins. The trick: loop coins on the outside and amounts on the inside, with dp[a] += dp[a - coin]. This order counts each combination once; swapping the loops counts orderings (permutations) instead.

Fewest perfect squares that sum to n. The trick: it is Coin Change where the “coins” are 1, 4, 9, 16, ... up to n. Same recurrence, same bottom-up fill.

Travel on given days and buy 1-, 7- or 30-day passes at minimum total cost. The trick: dp[day] is the cheapest cost to cover travel up to that day; each pass type is a “coin” that jumps back 1, 7 or 30 days.