Skip to main content
55

Coin Change

Mediumdynamic programmingbfs

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:1-D Dynamic ProgrammingRead the beginner guide

You're given coin values coins (you have unlimited coins of each value) and an amount. Return the fewest coins needed to make exactly amount. If it can't be made, return -1.

Understand the problem

  • You can use each coin value as many times as you want.
  • The coins must add up to exactly amount: not more, not less.
  • You want the smallest number of coins, not the number of ways.
  • Making 0 needs 0 coins.

Example 1

text
Input:  coins = [1, 2, 5], amount = 11
Output: 3

5 + 5 + 1 = 11: three coins. No combination of two coins reaches 11.

Example 2

text
Input:  coins = [2], amount = 3
Output: -1

With only 2s, you can make even amounts but never 3.

Example 3

text
Input:  coins = [1], amount = 0
Output: 0

Constraints

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    For every amount from 0 up to the target, work out the fewest coins needed by trying each coin as the last one: fewest[a] = 1 + min(fewest[a - coin]).

    Why "biggest coin first" fails

    The obvious strategy is greedy: always take the largest coin that still fits. It works for real currencies, which are designed for it, but not in general:

    text
    coins = [1, 3, 4], amount = 6
    greedy:  4 + 1 + 1   → 3 coins
    best:    3 + 3       → 2 coins

    Taking the 4 looked best right then, but it left an awkward 2. We need to consider every option without trying every combination.

    The key insight: look at the last coin

    Picture the best way to make amount a. Its last coin is one of the coin values c. Remove it, and what's left is a way to make a - c, which must itself use as few coins as possible (otherwise we could improve it).

    So, defining fewest[a] = the fewest coins that make amount a:

    text
    fewest[0] = 0                                  (zero coins make zero)
    fewest[a] = 1 + min(fewest[a - c])   over every coin c <= a

    Fill the table from 1 up to amount: every fewest[a - c] you need is for a smaller amount, so it's already computed. Amounts that can't be made stay at Infinity, and if fewest[amount] is still Infinity at the end, return -1.

    Step by step

    coins = [1, 3, 4], amount = 6:

    Amount aTry coin 1Try coin 3Try coin 4fewest[a]
    00
    1fewest[0] + 1 = 1too bigtoo big1
    2fewest[1] + 1 = 2too bigtoo big2
    3fewest[2] + 1 = 3fewest[0] + 1 = 1too big1
    4fewest[3] + 1 = 2fewest[1] + 1 = 2fewest[0] + 1 = 11
    5fewest[4] + 1 = 2fewest[2] + 1 = 3fewest[1] + 1 = 22
    6fewest[5] + 1 = 3fewest[3] + 1 = 2fewest[2] + 1 = 32

    Answer: 2 (3 + 3).

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    With A = amount and C = the number of coin values:

    • Time: O(A · C). For each amount, try each coin.
    • Memory: O(A) for the table.

    Common mistakes

    • Using greedy ("largest coin first"). Wrong on inputs like the one above.
    • Starting the table at 0 instead of Infinity. Then min always picks the fake 0, and "impossible" amounts look free.
    • Returning Infinity instead of converting it to -1.
    • Forgetting amount = 0. The answer is 0, and fewest[0] = 0 handles it.

    Going deeper

    • A graph view: think of each amount as a node, and each coin as an edge from a to a + c. The fewest coins is the shortest path from 0 to amount, which BFS can find level by level. It's a nice way to see why DP works.
    • Coin Change II asks for the number of ways to make the amount instead. It's a similar table, but the loops are arranged so each combination is counted only once.

    Reference solution

    js
    /**
     * @param {number[]} coins
     * @param {number} amount
     * @return {number}
     */
    export default function coinChange(coins, amount) {
      const fewest = new Array(amount + 1).fill(Infinity)
      // fewest[a] = fewest coins that make amount a. Infinity means "can't be made (yet)".
      fewest[0] = 0 // zero coins make zero
      // Smaller amounts first, so every fewest[a - coin] we need is already known.
      for (let a = 1; a <= amount; a++) {
        for (const coin of coins) {
          // Use this coin last: 1 coin plus the best way to make the rest.
          if (coin <= a) fewest[a] = Math.min(fewest[a], fewest[a - coin] + 1)
        }
      }
      // Still Infinity: no combination of coins makes this amount.
      return fewest[amount] === Infinity ? -1 : fewest[amount]
    }
    ts
    export default function coinChange(coins: number[], amount: number): number {
      const fewest = new Array<number>(amount + 1).fill(Infinity)
      // fewest[a] = fewest coins that make amount a. Infinity means "can't be made (yet)".
      fewest[0] = 0 // zero coins make zero
      // Smaller amounts first, so every fewest[a - coin] we need is already known.
      for (let a = 1; a <= amount; a++) {
        for (const coin of coins) {
          // Use this coin last: 1 coin plus the best way to make the rest.
          if (coin <= a) fewest[a] = Math.min(fewest[a], fewest[a - coin] + 1)
        }
      }
      // Still Infinity: no combination of coins makes this amount.
      return fewest[amount] === Infinity ? -1 : fewest[amount]
    }
    python
    def coin_change(coins: list[int], amount: int) -> int:
        # fewest[a] = fewest coins that make amount a. inf means "can't be made (yet)".
        # fewest[0] = 0: zero coins make zero.
        fewest = [0] + [float("inf")] * amount
        # Smaller amounts first, so every fewest[a - coin] we need is already known.
        for a in range(1, amount + 1):
            for coin in coins:
                # Use this coin last: 1 coin plus the best way to make the rest.
                if coin <= a:
                    fewest[a] = min(fewest[a], fewest[a - coin] + 1)
        # Still inf: no combination of coins makes this amount.
        return -1 if fewest[amount] == float("inf") else fewest[amount]