Approach 1Optimal▶ Animated
Fewest coins for each amount
dp[x] is the fewest coins that sum to x. Try every coin: dp[x] = min(dp[x], dp[x - coin] + 1).
This is unbounded knapsack. Amount 11 with {1,2,5} bottoms out at three 5+5+1 coins.
Algorithm
dp[0] = 0, everything else ∞.- For each amount, try each coin that fits.
- Return
dp[amount], or −1 if it stayed ∞.
- Time
- O(amount · k)
- Space
- O(amount)
class Solution: def coinChange(self, coins: list[int], amount: int) -> int: inf = amount + 1 dp = [inf] * (amount + 1) dp[0] = 0 for x in range(1, amount + 1): for c in coins: if c <= x: dp[x] = min(dp[x], dp[x - c] + 1) return dp[amount] if dp[amount] < inf else -1