Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

The fewest coins from a limited supply

Medium · Target 20 minutes · Dynamic programming

You hold counts[i] coins of value coins[i]. Return the fewest coins that pay exactly amount, or −1 if it cannot be paid with the coins you hold.

Examples

InputOutputWhy
coins = [1,2,5], counts = [3,2,1], amount = 1155 + 2 + 2 + 1 + 1.
coins = [1,5], counts = [10,1], amount = 735 + 1 + 1.
coins = [2], counts = [1], amount = 3-1Impossible.

Constraints

  • 1 ≤ coins.length ≤ 50
  • 1 ≤ coins[i] ≤ 10⁴, distinct
  • 1 ≤ counts[i] ≤ 1000
  • 0 ≤ amount ≤ 10⁴

Hints

Hint 1

fewest[t] = the fewest coins paying exactly t, ∞ if impossible; fewest[0] = 0.

Hint 2

Split each supply into bundles 1, 2, 4, …, remainder; a bundle of b coins adds b coins and b · value.

Hint 3

Run the 0/1 update with min, totals downwards, over the bundles.

Where people lose marks

  • Treating the supply as unlimited (the unbounded recurrence).
  • Initialising with 0 instead of ∞ for totals not yet reachable.
  • Bundles that exceed the supply.
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.