Coin Change - Problem
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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code