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 ProblemAvailable Coins134Infinite supply of eachTarget Amount6SolutionMinimum coins: 23+33 + 3 = 6 ✓Find the minimum number of coins to make the target amountDynamic programming builds optimal solutions for smaller amounts
Understanding the Visualization
1
Input
Available coin denominations and target amount
2
Process
Find optimal combination using fewest coins
3
Output
Return minimum number of coins needed
Key Takeaway
🎯 Key Insight: Use dynamic programming - if you know minimum coins for (amount - coin), then minimum for amount is 1 + min over all coins.
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