You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money.

Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.

You may assume that you have an infinite number of each kind of coin.

Input & Output

Example 1 — Basic Case
$ Input: coins = [1,3,4], amount = 6
Output: 2
💡 Note: 6 = 3 + 3, so minimum coins needed is 2
Example 2 — Impossible Case
$ Input: coins = [2], amount = 3
Output: -1
💡 Note: Cannot make amount 3 using only coins of denomination 2
Example 3 — Zero Amount
$ Input: coins = [1], amount = 0
Output: 0
💡 Note: No coins needed to make amount 0

Constraints

  • 1 ≤ coins.length ≤ 12
  • 1 ≤ coins[i] ≤ 231 - 1
  • 0 ≤ amount ≤ 104

Visualization

Tap to expand
Coin Change Problem - Dynamic Programming INPUT Coins Array: 1 3 4 Target Amount: 6 coins = [1, 3, 4] amount = 6 // Infinite supply ALGORITHM STEPS 1 Initialize DP Array dp[0]=0, dp[1..6]=INF 2 For each amount i Try all coins c where c<=i 3 Update dp[i] dp[i]=min(dp[i],dp[i-c]+1) 4 Return dp[amount] Or -1 if still INF DP Table: i: 0 1 2 3 4 5 6 0 1 2 1 1 2 2 dp[6] = min(dp[6-1]+1, dp[6-3]+1, dp[6-4]+1) FINAL RESULT Optimal Solution: 3 + 3 = 6 Output: 2 OK - Minimum coins found! 3 + 3 = 6 (2 coins) Key Insight: The DP approach builds solutions bottom-up: dp[i] represents the minimum coins needed for amount i. For each amount, we try all coins and take the minimum. Time: O(amount * coins), Space: O(amount). TutorialsPoint - Coin Change | Dynamic Programming Approach
Asked in
Amazon 45 Google 38 Microsoft 32 Facebook 28
78.0K Views
High Frequency
~25 min Avg. Time
1.9K 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