This is LeetCode #322: Coin Change — the classic DP problem! 🪙
💡 Think of it like this: You're at a vending machine that only takes certain coin types. You need to make exact change for a certain amount. What's the fewest coins you need?
The DP Approach: Build up from amount 0 to the target amount. For each amount, try every coin and pick the one that gives the fewest total coins.
Recurrence: dp[amount] = min(dp[amount - coin] + 1) for each valid coin
💭 Go for it! Apply the approach above in your own code. If you get stuck, use the hint below! 🔥
Step-by-step for coins=[1,3,4], amount=6:
Complexity: Time O(amount × len(coins)), Space O(amount).
def coinChange(coins, amount):
# dp[i] = fewest coins needed to make amount i
dp = [float('inf')] * (amount + 1)
dp[0] = 0 # 0 coins needed to make amount 0
for a in range(1, amount + 1):
for coin in coins:
if coin <= a: # Can we use this coin?
dp[a] = min(dp[a], dp[a - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
coinChange([1, 5, 6], 11)
2