Coin Change (Min Coins) visualization

Fewest coins summing to an amount, with unlimited coins of each denomination.

dp[x] = fewest coins for amount x. For each coin c ≤ x, dp[x] = min(dp[x], dp[x − c] + 1). dp[0] = 0.

Edge cases: amount 0 needs 0 coins; an amount no combination can make stays ∞ (return −1); zero or negative coins are rejected because they never make progress.

Complexity

Time: best O(A·k), average O(A·k), worst O(A·k). Space: O(A). Difficulty: Intermediate.

Pseudocode

procedure coinChange(coins, A):
  drop coins ≤ 0
  dp[0] ← 0; dp[1..A] ← ∞
  for x ← 1 to A:
    for c in coins:
      if c ≤ x and dp[x−c] + 1 < dp[x]: dp[x] ← dp[x−c] + 1
  return dp[A] if finite else −1

More dynamic programming algorithms