InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 1-D Dynamic Programming

Coin Change

medium Original ↗ 00:00

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 = 1135 + 5 + 1.
  • coins = [2], amount = 3-1 — odd target, only even coins.
  • coins = [1, 2, 5], amount = 00 — 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug