Fewest Coins for an Amount

MediumDynamic Programming≈ 35 min

You have an unlimited supply of coins of the values in coins. Return the fewest coins whose values add up to exactly amount, or -1 if the amount cannot be made from these coins at all. An amount of 0 takes no coins.

Examples

text
coins = [1, 2, 5], amount = 11   →  3
coins = [2], amount = 3          →  -1
coins = [1], amount = 0          →  0
coins = [1, 3, 4], amount = 6    →  2

In the first example 5 + 5 + 1 = 11. In the last, always taking the largest coin that fits gives 4 + 1 + 1, three coins, but 3 + 3 needs only two.

Constraints

  • Between 1 and 12 coin values, each between 1 and 10,000, all different; amount is between 0 and 10,000.
  • Aim for O(amount × coins): one step for every amount up to the target and every coin.
Sound off. Turn on for key clicks and a chime when the tests pass.Inline suggestions off. Recommended while you are learning. Turn on to complete words as you type.
Console
›Run to see what your code prints

Run checks the 4 visible cases here, in your browser. Submit runs all 9 on the judge, 5 of them hidden, and measures how your solution scales.