sagelearnai

Coin Change

Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #322

Given coin denominations coins (unlimited supply of each) and a target amount, return the fewest coins that add up to exactly amount, or −1 if it can't be done. amount = 0 needs 0 coins.

Examples

text
coins = [1, 5, 6, 9], amount = 11  →  2    (5 + 6)
coins = [2], amount = 3            →  −1
coins = [1], amount = 0            →  0

Hints

  1. Greedy (always take the largest coin) fails: for 11 with [1,5,6,9], it gives 9+1+1 = 3 coins.
  2. dp[a] = minimum coins to make amount a.
  3. The last coin used is some c, so dp[a] = 1 + dp[a − c] minimized over c.

Approach

State: dp[a] = fewest coins to make a. Base: dp[0] = 0; others start at ∞. For each a from 1 to amount, and each coin c ≤ a: dp[a] = min(dp[a], dp[a − c] + 1). The answer is dp[amount], or −1 if it's still ∞. This is the unbounded knapsack pattern: coins can repeat because dp[a − c] may already use c.

Complexity

Time: O(amount × len(coins)). Space: O(amount).

Python solution
def coinChange(coins, amount):
    INF = amount + 1
    dp = [0] + [INF] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and dp[a - c] + 1 < dp[a]:
                dp[a] = dp[a - c] + 1
    return dp[amount] if dp[amount] != INF else -1
JavaScript solution
function coinChange(coins, amount) {
  const INF = amount + 1, dp = new Array(amount + 1).fill(INF);
  dp[0] = 0;
  for (let a = 1; a <= amount; a++) for (const c of coins) if (c <= a) dp[a] = Math.min(dp[a], dp[a - c] + 1);
  return dp[amount] === INF ? -1 : dp[amount];
}