13. Coin Change

Difficulty:MediumPattern:Dynamic ProgrammingTime:O(amount * n)Space:O(amount)

Given an integer array coins and an integer amount, return the fewest number of coins needed to make up that amount.

How It Works & Algorithmic Design

Solves using Bottom-Up Unbounded Knapsack Dynamic Programming:

  1. DP Array: Create array dp of size amount + 1, filled with Infinity. Set dp[0] = 0 (0 coins needed for amount 0).
  2. State Transition: For $i$ from $1$ to amount:
    • Loop each coin in coins:
    • If $i - \text{coin} \ge 0$, update dp[i] = Math.min(dp[i], dp[i - coin] + 1).
  3. Result: Return dp[amount] === Infinity ? -1 : dp[amount].

Why This Approach Works Best

Greedy choice fails for arbitrary coin denominations (e.g., coins [1, 3, 4], amount 6 -> Greedy picks 4+1+1 (3 coins) vs DP optimal 3+3 (2 coins)). DP guarantees exact minimal count in $O(\text{amount} \times \text{coins.length})$ time.

Example Walkthrough

Input

coins = [1, 2, 5], amount = 11

Target total 11.

DP State

dp[11] = min(dp[10]+1, dp[9]+1, dp[6]+1) = 3 (5 + 5 + 1)

Minimum coins needed.

Output

3

3 coins.

Answer: Coin Change using Dynamic Programming

function coinChange(coins, amount) {
  const dp = new Array(amount + 1).fill(Infinity);
  dp[0] = 0;
  for (let i = 1; i <= amount; i++) {
    for (const coin of coins) {
      if (i - coin >= 0) {
        dp[i] = Math.min(dp[i], dp[i - coin] + 1);
      }
    }
  }
  return dp[amount] === Infinity ? -1 : dp[amount];
}

Build optimal minimum coin state array bottom-up.

Key Takeaways
  • Greedy coin selection fails for arbitrary denominations.

  • Bottom-up DP checks all valid coin combinations efficiently.

  • Time complexity $O(A \cdot N)$ where $A$ is amount and $N$ is coin count.