PracticeNeetCode ↗LeetCode ↗
Given coin denominations coins (unlimited supply of each) and a target amount, return the fewest coins needed to make that amount. If it can't be made, return -1.
dp, an array of size amount + 1, filled with the sentinel amount + 1, then set dp[0] = 0.dp[a] = min(dp[a], 1 + dp[a - coin]).dp[amount] holds either the true minimum or the untouched sentinel.dp[amount] if it isn't the sentinel, otherwise -1.Time: O(amount · len(coins)) — Space: O(amount)
def coinChange(coins: list[int], amount: int) -> int:
dp = [amount + 1] * (amount + 1)
dp[0] = 0
for a in range(1, amount + 1):
for coin in coins:
if coin <= a:
dp[a] = min(dp[a], 1 + dp[a - coin])
return dp[amount] if dp[amount] != amount + 1 else -1How the solution above works, piece by piece.
dp[a] = the fewest coins that sum to a. It starts at amount + 1, an impossible count that acts as infinity.dp[0] = 0: zero coins make zero.1 + dp[a - coin] uses one coin plus the best way to make the rest.dp[a - coin] is always ready when needed.dp[amount] is still the sentinel, it can't be made → −1. O(amount × coins) time.Running it on coins = [1, 2, 5], amount = 11:
dp[a] = 1 + min(dp[a − coin]). Blue cells trace how 11 is built: 11 → 6 → 1 → 0, using coins 5, 5 and 1.