Coin Change

Implement coinChange

A cashier has an unlimited supply of coins in several denominations and owes a customer a specific amount of change. Working out the minimum number of coins the cashier could hand over — using each denomination as many times as needed — is the goal; if the denominations available simply can't add up to that exact amount, the answer should signal that paying it precisely is impossible. Handing over nothing at all pays off an amount of zero — that's the natural stopping point every path eventually reaches. Whenever a positive amount is still owed, picking any single denomination as the next coin handed over leaves a smaller remaining amount that faces the identical question all over again. Since a denomination isn't used up after being picked once, it stays available to be picked again on the very next step. Trying every denomination at every remaining amount, and keeping track of whichever choice leads to the fewest coins overall, builds up the answer from the smallest amounts toward the full one.

Example 1:

Input: coins = [2,5,7], amount = 12

Output: 2

Example 2:

Input: coins = [3], amount = 7

Output: -1

Example 3:

Input: coins = [1,3,4], amount = 6

Output: 2

+ 7 hidden test cases run on Submit.

Constraints:

  • 1 ≤ coins.length ≤ 15
  • 1 ≤ coins[i] ≤ 100
  • 0 ≤ amount ≤ 1000

coins =

[2, 5, 7]

amount =

12