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 make an amount

Medium · Target 15 minutes · Dynamic programming · Type asked atAmazonGoogleBloomberg

Given an amount and a list of distinct coin values coins, with an unlimited supply of each, return the number of combinations of coins that add up to the amount. Combinations that differ only in order count once. If the amount is 0, there is one way: no coins.

Examples

InputOutputWhy
amount = 5, coins = [1,2,5]45; 2+2+1; 2+1+1+1; 1+1+1+1+1.
amount = 3, coins = [2]0Odd amounts cannot be made from 2s.
amount = 0, coins = [7]1The empty combination.

Constraints

  • 1 ≤ coins.length ≤ 300
  • 1 ≤ coins[i] ≤ 5000, all distinct
  • 0 ≤ amount ≤ 5000
  • The answer fits in a 64-bit integer

Hints

Hint 1

ways[0] = 1. For each coin, ways[a] += ways[a − coin] for a from coin upwards.

Hint 2

Coins must be on the outer loop. With amounts outside, 1 + 2 and 2 + 1 are counted separately.

Where people lose marks

  • Amounts on the outer loop, which counts ordered sequences (9 instead of 4 for the first example).
  • Starting with ways[0] = 0, which makes every count 0.
  • Overflow in 32-bit integers for large inputs.
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.