AlgoFrames

Coin change: minimum coins and number of ways

Coin change finds the fewest coins for an amount, or the number of ways to make it. Each coin sweeps across the amounts table.

Before you start: 0/1 and unbounded knapsack.

Fewest coins for an amount

The idea

Coins come in values 1, 3 and 4, with as many of each as you like. What is the fewest number of coins that make 6?

Intuition

Taking the biggest coin first gives 4 + 1 + 1, three coins. Two 3s make 6 with only two coins.

Greedy works for coin systems like 1, 5, 10, 25, but not for every set. A 4 leaves 2, and 2 needs two coins; a 3 leaves 3, which needs one.

Any way to make 6 ends with a 1, a 3 or a 4. So dp[6] = 1 + the smallest of dp[5], dp[3] and dp[2].

Remove the last coin c and the rest makes 6 − c. The rest should use as few coins as possible, which is dp[6 − c]. Smaller amounts are solved first.

Complexity

Each of k coins sweeps amounts up to A once, in O(1) per cell: O(A · k) time and O(A) space for one array.

Pitfalls

Some amounts cannot be made. They must stay ∞ and the answer becomes −1, not a count built from a fake 0.

In Java or C++, Integer.MAX_VALUE + 1 overflows to a negative number and wins every min. Skip a source that is still ∞, or use amount + 1 as the infinity.

dp[0] must be 0. If it starts at ∞ like the others, no amount can ever be reached.

Variations

Coin change II counts ways instead: dp[0] = 1 and each cell adds dp[a − c] instead of taking a minimum.

Perfect squares is coin change where the coins are 1, 4, 9, 16 and so on, up to n.

Counting the ways to make change

The idea

Coins 1, 2 and 5 make 5 in four ways. How do we count them without listing every one?

Intuition

dp[a] counts coin sets that make a. dp[0] = 1, because choosing no coins is one way to make 0.

Every set that ends with coin c is a set for a − c plus one c. Starting from the one empty set, those counts build up amount by amount.

Let each coin sweep the whole table before the next coin starts. Sets are then built in coin order, so 1 + 2 and 2 + 1 count once.

When coin 2 is processed, coin 1 has finished. A set can only add a 2 after its 1s, never a 1 after a 2, so each set has exactly one build order.

Complexity

The same sweep as fewest coins: O(A · k) time and one array of A + 1 counts, O(A) space.

Pitfalls

Swapping the loops, amounts outside and coins inside, counts 1 + 2 and 2 + 1 as two ways. That answers a different question.

With dp[0] = 0 every cell adds zeros and the answer is always 0. The empty set has to count as one way.

Variations

Combination sum IV wants ordered sequences. There the amount loop goes outside, so 1 + 3 and 3 + 1 both count.

Counting subsets where each item is used once is 0/1 knapsack with counts. The sweep then runs right to left.

Code

Pseudocode

coinChange(coins, amount):
  dp ← array of amount + 1 values, all ∞
  dp[0] ← 0
  for each coin c in coins
    for a ← c to amount
      dp[a] ← min(dp[a], dp[a - c] + 1)
  if dp[amount] = ∞: return -1
  return dp[amount]

Python

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

JavaScript

function coinChange(coins, amount) {
  const dp = new Array(amount + 1).fill(Infinity);
  dp[0] = 0;
  for (const c of coins) {
    for (let a = c; a <= amount; a++) {
      dp[a] = Math.min(dp[a], dp[a - c] + 1);
    }
  }
  return dp[amount] === Infinity ? -1 : dp[amount];
}

Java

static int coinChange(int[] coins, int amount) {
    int[] dp = new int[amount + 1];
    Arrays.fill(dp, Integer.MAX_VALUE);
    dp[0] = 0;
    for (int c : coins)
        for (int a = c; a <= amount; a++)
            if (dp[a - c] != Integer.MAX_VALUE) dp[a] = Math.min(dp[a], dp[a - c] + 1);
    return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
}

Practice problems (6)

Fill the coin table Warm-up

Coins 1, 2 and 5 make amounts up to 7. Follow the fewest-coins table and answer each question before the step plays.

When does greedy fail? Warm-up

Greedy change takes the biggest coin that still fits, again and again. For which coins and amount does it use more coins than needed?

Coin change Standard

coins holds coin values; you have unlimited coins of each value. Return the fewest coins that add up to exactly amount, or -1 if no mix of coins does.

Coin change II Standard

Return the number of different coin sets that add up to amount, using unlimited coins of each value in coins. Sets that differ only in order count once. Return 0 if no set works.

Perfect squares Standard

Return the fewest perfect squares (1, 4, 9, 16, …) that add up to n. A square may be used more than once.

Combination sum IV Challenge

nums holds distinct positive numbers. Return how many ordered sequences of numbers from nums add up to target. Numbers may repeat, and different orders count separately, so 1 + 2 and 2 + 1 are two sequences.

Related topics

Next on the path: Longest increasing subsequence; the n log n version