Command Palette

Search for a command to run...

Problem 30.5 · Knapsack DPMedium

Coin Change II

What it teaches: Counting combinations: coins in the outer loop.

Practise it on judges as “Coin Change II”.

The problem

Return the number of combinations of coins (unlimited supply) that make up amount. Order doesn't matter.

Example 1

Input: amount = 5, coins = [1, 2, 5]
Output: 4

Constraints

  • 1 ≤ coins ≤ 300
  • 0 ≤ amount ≤ 5000

Pattern clues in the wording

  • → Number of ways, order irrelevant

These clues point to Knapsack DP: For each item, decide take or skip under a capacity; dp[c] is the best result using capacity c.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int change(int amount, int[] coins) {
        return 0;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
amount = 5
coins = [1,2,5]
4
2
amount = 3
coins = [2]
0
3
amount = 10
coins = [10]
1

From slow to fast

Approaches

1

Unbounded counting DP

Time O(amount × coins) Space O(amount)

ways[0] = 1; for each coin, for a from coin to amount: ways[a] += ways[a − coin].

Approach 1
class Solution {
    public int change(int amount, int[] coins) {
        int[] ways = new int[amount + 1];
        ways[0] = 1;
        for (int c : coins)
            for (int a = c; a <= amount; a++) ways[a] += ways[a - c];
        return ways[amount];
    }
}

Verdict: The loop order is the lesson.

Before you submit

Edge cases and common mistakes

Test these inputs

  • amount = 0 (1 way: no coins)
  • No combination (0)

Mistakes people make

  • Amount-outer loop (counts orderings).

Interview

Follow-up questions

How would you count combinations using each coin at most once?