InterviewPrepKit

Home / Coding / 1-D Dynamic Programming

Coin Change

medium Original β†—
Solving tips
  • Recognize unbounded-knapsack min-over-choices DP: dp[a] = 1 + min over coins c<=a of dp[a-c], with dp[0]=0.
  • Greedy 'take the largest coin' is wrong for arbitrary denominations (e.g. [1,3,4] for 6), so commit to the DP.
  • Use amount+1 as the infinity sentinel (no real answer exceeds amount coins) and return -1 if dp[amount] stays at it.
  • Target O(amount * #coins) time, O(amount) space; the table cannot collapse to scalars since dp[a] can depend on cells far back.

Problem

You are given a list of coins of distinct denominations and an integer amount. You have an unlimited supply of each coin. Return the fewest number of coins whose values sum to exactly amount. If no combination sums to amount, return -1.

Examples

  • coins = [1, 2, 5], amount = 11 β†’ 3 β€” 5 + 5 + 1.
  • coins = [2], amount = 3 β†’ -1 β€” odd target, only even coins.
  • coins = [1, 2, 5], amount = 0 β†’ 0 β€” zero coins make zero.

Constraints

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

amount up to 10^4 and few coin types means an O(amount Γ— len(coins)) DP is the intended fit. Greedy β€œtake the biggest coin first” is wrong in general (e.g. coins = [1, 3, 4], amount = 6: greedy takes 4+1+1 = 3 coins, but 3+3 = 2 is optimal).

Think about it first

Hint 1 Suppose you knew the fewest coins for every amount smaller than the target. The last coin you place must be one of the denominations β€” which subproblem does removing it leave you with?
Hint 2 `fewest(a) = 1 + min over each coin c (with c <= a) of fewest(a - c)`. Base case `fewest(0) = 0`. If no coin leads to a solvable subproblem, `a` is unreachable.
Hint 3 Build a table `dp[0 .. amount]`, initialize `dp[0] = 0` and everything else to "infinity," and fill upward. For each amount `a` try every coin. At the end, `dp[amount]` is the answer, or `-1` if it stayed infinite. O(amount Γ— #coins) time.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.