Imagine you're working as a cashier and need to make change using the fewest coins possible. You have an unlimited supply of coins with specific denominations, and you need to find the most efficient way to make exact change.

Given an integer array coins representing different coin denominations and an integer amount representing the total money you need to make, return the minimum number of coins needed to make up that exact amount.

If it's impossible to make the exact amount with the given coins, return -1.

Example: With coins [1, 3, 4] and amount 6, you could use [3, 3] (2 coins) or [1, 1, 4] (3 coins). The optimal solution uses only 2 coins.

Input & Output

example_1.py โ€” Basic Case
$ Input: coins = [1, 3, 4], amount = 6
โ€บ Output: 2
๐Ÿ’ก Note: The optimal solution is to use two coins of value 3: [3, 3]. This gives us exactly 6 with only 2 coins, which is better than alternatives like [1,1,4] (3 coins) or [1,1,1,3] (4 coins).
example_2.py โ€” Impossible Case
$ Input: coins = [2], amount = 3
โ€บ Output: -1
๐Ÿ’ก Note: It's impossible to make amount 3 using only coins of value 2. Since 3 is odd and we only have even-valued coins, no combination can sum to 3.
example_3.py โ€” Zero Amount
$ Input: coins = [1], amount = 0
โ€บ Output: 0
๐Ÿ’ก Note: To make amount 0, we need 0 coins. This is the base case - no coins are needed to make no money.

Constraints

  • 1 โ‰ค coins.length โ‰ค 12
  • 1 โ‰ค coins[i] โ‰ค 231 - 1
  • 0 โ‰ค amount โ‰ค 104
  • All coin denominations are positive integers

Visualization

Tap to expand
๐Ÿช™ Smart Cashier's Learning Process"I'll learn the best way to make each amount and remember it!"Coins available: [1, 3, 4] | Target: 60โ†’0Free!1โ†’11 coin2โ†’22 coins3โ†’1Better!4โ†’1Even better!5โ†’24+16โ†’2ANSWER!For amount 6: Try all coins and pick the bestโ€ข Use coin 1: 1 + (best for 5) = 1 + 2 = 3 coinsโ€ข Use coin 3: 1 + (best for 3) = 1 + 1 = 2 coins โญโ€ข Use coin 4: 1 + (best for 2) = 1 + 2 = 3 coins๐ŸŽฏ Optimal Solution: 2 coins (3 + 3)Time: O(amount ร— coins) | Space: O(amount)Each amount calculated once and reused - no wasted work!
Understanding the Visualization
1
Start with basics
Amount 0 needs 0 coins (obvious!)
2
Build up gradually
For each amount, try each coin and use the best previous result
3
Reuse knowledge
Each amount is calculated once and reused
4
Get final answer
The target amount now contains the optimal solution
Key Takeaway
๐ŸŽฏ Key Insight: Dynamic programming eliminates redundant work by solving each subproblem exactly once and reusing the results. The optimal substructure means we can build complex solutions from simpler ones.
Asked in
Amazon 85 Google 72 Meta 58 Microsoft 45 Apple 38
89.2K Views
Very High Frequency
~25 min Avg. Time
2.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