Coin Change II - Problem
Coin Change II presents a classic dynamic programming challenge in combinatorics. You're given an array of coins representing different denominations and an integer amount representing a target sum. Your goal is to find how many different ways you can combine these coins to make exactly that amount.

Key points:
• You have an unlimited supply of each coin type
• Order doesn't matter - [1,2] and [2,1] count as the same combination
• If the amount cannot be made, return 0
• The result fits in a 32-bit integer

For example, with coins [1, 2, 5] and amount 5, there are 4 ways: [5], [2,2,1], [2,1,1,1], [1,1,1,1,1].

Input & Output

example_1.py — Basic Case
$ Input: coins = [1,2,5], amount = 5
Output: 4
💡 Note: There are 4 ways to make amount 5: [5], [2,2,1], [2,1,1,1], [1,1,1,1,1]
example_2.py — No Solution
$ Input: coins = [2], amount = 3
Output: 0
💡 Note: Amount 3 cannot be made with only coin value 2 (odd amount with even coins)
example_3.py — Zero Amount
$ Input: coins = [10], amount = 0
Output: 1
💡 Note: There is exactly one way to make amount 0: use no coins at all

Constraints

  • 1 ≤ coins.length ≤ 300
  • 1 ≤ coins[i] ≤ 5000
  • 0 ≤ amount ≤ 5000
  • All coin values are positive integers
  • The answer is guaranteed to fit in a signed 32-bit integer

Visualization

Tap to expand
Coin Change II - Dynamic Programming INPUT Coin Denominations: 1 2 5 coins = [1, 2, 5] amount = 5 Goal: Count ways to make amount using coins Unlimited supply of each coin ALGORITHM STEPS 1 Initialize DP Array dp[0]=1, rest=0 2 For each coin Process coins: 1, 2, 5 3 Update DP Table dp[i] += dp[i-coin] 4 Return dp[amount] Answer at dp[5] DP Table (after all coins): i: 0 1 2 3 4 5 dp: 1 1 2 2 3 4 dp[i] += dp[i - coin] FINAL RESULT Output: 4 4 different combinations All Valid Combinations: 1. 5 = 5 2. 2 + 2 + 1 = 5 3. 2 + 1 + 1 + 1 = 5 4. 1 + 1 + 1 + 1 + 1 = 5 OK - Verified Key Insight: By iterating coins in the outer loop and amounts in the inner loop, we avoid counting permutations as different combinations. Each coin is considered once, building up valid combinations incrementally. Time: O(n * amount), Space: O(amount) TutorialsPoint - Coin Change II | Dynamic Programming Approach
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
42.4K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen