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

Ways to pay with a limited supply

Medium · Target 20 minutes · Dynamic programming

You hold counts[i] coins of value coins[i] (values distinct). Return the number of different combinations, as a multiset of coins, that pay exactly amount. Paying 0 has one way.

Examples

InputOutputWhy
coins = [1,2,5], counts = [3,2,1], amount = 535; 2 + 2 + 1; 2 + 1 + 1 + 1.
coins = [1,2], counts = [2,2], amount = 422 + 2; 2 + 1 + 1.
coins = [3], counts = [1], amount = 60Only one 3.

Constraints

  • 1 ≤ coins.length ≤ 50
  • 1 ≤ counts[i] ≤ 1000
  • 0 ≤ amount ≤ 10⁴
  • The answer fits in a 64-bit integer

Hints

Hint 1

ways[t] after coin i = Σ over k = 0..counts[i] of old ways[t − k · c].

Hint 2

That sum slides: it is the previous term for t − c plus old[t] minus old[t − (counts + 1) · c].

Hint 3

Binary splitting into bundles overcounts: two bundle choices can give the same number of coins.

Where people lose marks

  • Binary splitting the supply, which overcounts.
  • Forgetting to subtract the term that falls out of the window.
  • Counting ordered sequences instead of combinations.
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.