Practice · Dynamic programming (1D) · 3 of 8

Fewest Coins for an Amount

You have coins worth each of the values in coins, as many of each as you like. Return the fewest coins that add up to exactly amount, or -1 if no combination of coins does.

An amount of 0 takes no coins.

Example 1

Input
coins = [1, 2, 5], amount = 11
Output
3
5 + 5 + 1 = 11.

Example 2

Input
coins = [2], amount = 3
Output
-1
Coins worth 2 only ever make even amounts.

Example 3

Input
coins = [1, 3, 4], amount = 6
Output
2
3 + 3. Taking the biggest coin first (4 + 1 + 1) needs three coins.

Constraints

  • coins holds 1 to 12 different values.
  • 1 ≤ coins[i] ≤ 10⁴
  • 0 ≤ amount ≤ 10⁴