Skip to content
Work Free practice Coding course Blog Method Results Why me About Enquire Book a call

Coding · Dynamic programming

Fewest coins to make an amount

Medium · Target 20 minutes · Dynamic programming · Type asked atCitadelBloombergMeta

You have an unlimited supply of coins of each denomination in coins. Return the fewest coins that add up to amount, or -1 if it cannot be done.

Examples

InputOutputWhy
coins = [1, 5, 10, 25], amount = 30225 + 5.
coins = [1, 3, 4], amount = 623 + 3. Greedy would take 4 + 1 + 1 and use three.
coins = [2], amount = 3-1Odd amounts are unreachable with a single even coin.

Constraints

  • 1 ≤ |coins| ≤ 12
  • 1 ≤ coins[i] ≤ 2³¹ − 1
  • 0 ≤ amount ≤ 10⁴

Hints

Hint 1

Try the greedy "take the largest coin that fits" on coins = [1, 3, 4] and amount = 6. It gives 3 coins; the answer is 2.

Hint 2

Write the recursion first: best(a) = 1 + min over coins c ≤ a of best(a − c), with best(0) = 0.

Hint 3

That recursion asks for the same amounts over and over. Fill an array from 0 upwards instead.

Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.