MediumArrayDynamic ProgrammingBreadth-First Search

1 approach, code in every language

Problem description

You are given a list of coin denominations and a target amount of money. You may use each denomination any number of times.

Return the fewest number of coins needed to make up the target amount exactly. If no combination of the given coins sums to the amount, return -1.

Example 1

Input: coins = [1, 2, 5], amount = 11

Output: 3

The amount 11 can be formed as 5 + 5 + 1, which uses three coins and no smaller count is possible.

Example 2

Input: coins = [2], amount = 3

Output: -1

With only the denomination 2 available, the odd amount 3 can never be reached, so the answer is -1.

Constraints

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4

After the pattern

Now solve one you haven't seen.

Fewest Tokens for the Charge is our own problem on the technique behind Coin Change: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free