Coding Interview PatternsCoin Change II
MediumDynamic Programming
Coin Change II
Explanation & Solution
Description
You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.
Return the number of combinations that make up that amount. If that amount of money cannot be made up by any combination of the coins, return 0.
You may assume that you have an infinite number of each kind of coin.
The answer is guaranteed to fit into a signed 32-bit integer.
Input:amount = 5, coins = [1,2,5]
0
1
1
2
2
5
Output: 4
Explanation: There are four ways to make up the amount:
5 = 55 = 2 + 2 + 15 = 2 + 1 + 1 + 15 = 1 + 1 + 1 + 1 + 1
Constraints
1 <= coins.length <= 3001 <= coins[i] <= 5000- All the values of
coinsare unique 0 <= amount <= 5000
Approach
Dynamic Programming pattern
1. Define the DP Array
- Create an array
dpof sizeamount + 1, initialized to0 dp[i]represents the number of combinations that make up amounti- Set
dp[0] = 1because there is exactly one way to make amount 0: use no coins
2. Iterate Over Each Coin
- Loop through each coin denomination in the
coinsarray - For each coin, we update the DP array to include combinations using that coin
- Processing coins in the outer loop ensures we count combinations, not permutations
3. Update the DP Array
- For each coin, iterate
jfromcointoamount - For each
j, adddp[j - coin]todp[j] - This means: the number of ways to make amount
jincreases by the number of ways to makej - coin(since we can add one more of the current coin)
4. Return the Result
- After processing all coins,
dp[amount]contains the total number of combinations - Return
dp[amount]
Key Insight
- By iterating coins in the outer loop and amounts in the inner loop, each combination is counted exactly once (e.g.,
[1,2]and[2,1]are treated as the same combination) - This is an unbounded knapsack variant where we can use each coin unlimited times
Time
O(n * amount) where n is the number of coin denominationsSpace
O(amount) for the 1D DP arrayVisualization
Input:
Dynamic Programmingamount = 5, coins = [1,2,5]
dp
Press play to start DP animation
ComputingDependencyFilledEmpty
12 steps