ExamAdda Logo

Coin Change

Easy

You are given an integer array coins representing different denominations of coins and an integer amount representing a total amount of money.

Return the fewest number of coins needed to make up the given amount.

You may use each coin denomination unlimited times.

If the amount cannot be made up using the given coins, return -1.

Example 1

Input

n = 3
coins = [1, 2, 5]
amount = 11

Output

3

Explanation

The minimum number of coins is:

5 + 5 + 1 = 11

 

So the answer is 3.

Example 2

Input

n = 1
coins = [2]
amount = 3

Output

-1

Explanation

It is impossible to make amount 3 using only coins of denomination 2.

Constraints

1 <= coins.length <= 12
1 <= coins[i] <= 2^31 - 1
0 <= amount <= 10^4
Each coin denomination is unique.

Hints:

Hint 1

Let dp[i] represent the minimum number of coins needed to make amount i.

Hint 2

For every coin, if the current amount is at least the coin value:

dp[i] = min(dp[i], dp[i - coin] + 1)

Auto
Loading editor...
Input

Expected Output