Coin Change
Use unlimited copies of the positive denominations to make target exactly. Return the minimum number of coins, or -1.
Use unlimited copies of the positive denominations to make target exactly. Return the minimum number of coins, or -1.
Input and constraints
- Each value must be positive.
- Target must be between 0 and 100.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): dp = [0] * ((target + 1)) amount = 1 while (amount <= target): dp[amount] = (target + 1) i = 0 while (i < len(values)): coin = values[i] if (coin <= amount): dp[amount] = min(dp[amount], (dp[(amount - coin)] + 1)) i = (i + 1) amount = (amount + 1) if (dp[target] > target): return -1 return dp[target]Visualizer
Step 1 of 14Inspect the current state
Try a final coin of 1 for amount 1.
Variable watch
Step explanation
Try a final coin of 1 for amount 1.
Worked explanation
A change counter writes the minimum number of coins on each smaller amount card.
Guided solution
For each amount, try each possible last coin and keep the shortest reachable predecessor plus one.
O(t × n) time · O(t) auxiliary space
Examples
Worked example · {"values":[1,3,4],"target":6} ⇒ 2
Edge case 1 · {"values":[4,6],"target":5} ⇒ -1
Edge case 2 · {"values":[],"target":0} ⇒ 0
Edge case 3 · {"values":[],"target":3} ⇒ -1
Progressive hints
Hint 1
A change counter writes the minimum number of coins on each smaller amount card.Hint 2
For each amount, try each possible last coin and keep the shortest reachable predecessor plus one.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
Taking the largest coin first can fail for denominations such as 1, 3, 4.
Interview follow-up
How would you reconstruct the actual chosen coins?