Coin Change

Medium1-D dynamic programming

You have coins of the values in coins, as many of each as you need. Return the fewest coins that add up to exactly amount.

Return -1 if no mix of coins makes that amount. An amount of 0 needs no coins.

Examples

Example 1
Input:  coins = [1, 4, 5], amount = 8
Output: 2

4 + 4. Starting with the 5 leaves 3, which takes three 1s: four coins.

Example 2
Input:  coins = [3, 7], amount = 5
Output: -1

No mix of 3s and 7s adds up to 5.

Constraints

  • 1 ≤ coins.length ≤ 12
  • 1 ≤ coins[i] ≤ 2³¹ - 1
  • 0 ≤ amount ≤ 10⁴

Stuck?

Hint 1

Always taking the biggest coin that fits can miss the best answer. Instead, work out the fewest coins for every amount from 0 up to amount.

Hint 2

For each amount a, try every coin c ≤ a: the answer is one more than the best for a - c. Start every amount at Infinity, and amount 0 at 0.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur