Skip to content
Onsite

Coin Change

MediumP1Coding

Given an array coins of distinct positive denominations and an integer amount, return the fewest coins needed to make exactly amount, using each denomination any number of times. If it cannot be made, return -1. An amount of 0 needs 0 coins.

Example 1

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

Example 2

Input
coins = [2], amount = 3
Output
-1

Example 3

Input
coins = [1], amount = 0
Output
0

Constraints

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

Hints

Run checks the 3 visible tests, Submit all 11.