Menu
CoddyTech

Coin Change

You get a list coins of different coin values and a target amount. You may use each coin value as many times as you want. Return the smallest number of coins whose values add up to exactly amount, or -1 if no mix of coins reaches it. An amount of 0 needs 0 coins.

Function

coinChange(coins: integer-array, amount: integer) → integer
coinsinteger-array
the different coin values, each usable any number of times
amountinteger
the total to pay exactly
Returnsinteger
the fewest coins needed, or -1 when the amount cannot be made

Constraints

  • 1 ≤ coins.length ≤ 12
  • 1 ≤ coins[i] ≤ 104
  • 0 ≤ amount ≤ 104
  • All coin values are different.

Examples

Input
coins = [2, 5, 10]amount = 27
Output
4
Explanation
10 + 10 + 5 + 2 makes 27 with four coins. Three coins fail: 27 is odd, so they need exactly one 5, and the other two add at most 20, short of 22.
challenge icon

Follow-up

Can you count how many different combinations of coins add up to amount, instead of finding the fewest coins?

Reset code
def coinChange(coins, amount):
    # Write code here

Test #1

Test #2

Test #3

Arguments

coins = [2, 5, 10]
amount = 27

Expected Output

4