Coin Change medium
Description
You’re given coin denominations coins[] and a target amount. Return the fewest number of coins that sum to amount. Each coin can be used an unlimited number of times. If the amount can’t be made, return -1.
Examples
> Case 1:
coins = [1, 2, 5], amount = 11
Output: 3
Explanation: 11 = 5 + 5 + 1.
> Case 2:
coins = [2], amount = 3
Output: -1
> Case 3:
coins = [1], amount = 0
Output: 0Constraints
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10^4
State design
This is unbounded knapsack in its purest form — pick coins (items) with repetition, minimize count, subject to a fixed sum.
- What am I computing?
dp[w]= min coins to make amountw. - Dimensions? One —
w. - Base cases?
dp[0] = 0(zero coins for zero amount). Mark all otherdp[w]as infinity / unreachable. - Transition? For each amount
w, try every coinc <= w:dp[w] = min(dp[w], dp[w - c] + 1). - Order? Amount
wfrom 1 toamount. (Eachdp[w]readsdp[w - c]for smallerw.) - Answer?
dp[amount], or-1if it stayed at infinity.
The greedy “always take the largest coin first” doesn’t work in general. For coins = [1, 3, 4], amount = 6: greedy gives 4 + 1 + 1 = 3 coins, but optimal is 3 + 3 = 2 coins. DP is required. For specific currency systems (US dollars, euros) greedy happens to be optimal — but never assume it.
Code
Why use amount + 1 as infinity instead of INT_MAX? Because dp[w - c] + 1 might overflow if you start from INT_MAX. And no legitimate answer can exceed amount (the worst case is using amount ones), so amount + 1 is a safe sentinel.
Analysis
- Time:
O(amount × len(coins)). - Space:
O(amount).
The closely-related cousin: Coin Change II
Count the number of distinct ways to make
amountusing unlimited coins.
Same state, different operator, and a different loop order — to count combinations (unordered), iterate coins in the outer loop:
def change(amount, coins):
dp = [0] * (amount + 1)
dp[0] = 1
for c in coins: # coins outside
for w in range(c, amount + 1): # amount inside
dp[w] += dp[w - c]
return dp[amount]Swap the loops and you’d count permutations (ordered) — a different problem.