Coin Change

Medium Dynamic Programming AI round

coins lists the values of the kinds of coin you have, and amount is a sum of money to pay exactly.

You have as many coins of each kind as you need: a kind can be used any number of times, or not at all.

Return the fewest coins whose values add up to exactly amount, or -1 if no mix of the coins does.

Example 1

Input: coins = [2,5,7], amount = 16
Output: 3

7 + 7 + 2 = 16 takes 3 coins. Two coins make at most 7 + 7 = 14, so no mix takes fewer.

Example 2

Input: coins = [4,6], amount = 9
Output: -1

Example 3

Input: coins = [3], amount = 0
Output: 0

Constraints

  • 1 ≤ coins.length ≤ 10
  • 1 ≤ coins[i] ≤ 10⁴
  • The values in coins are all different
  • 0 ≤ amount ≤ 10⁴

Watch the explanation

More Dynamic Programming

All Dynamic Programming problems