☰ All problems

55. Coin Change

You are given the coin denominations coins (you have an unlimited supply of each) and a target amount.

Return the fewest coins whose values add up to exactly amount. If no combination of coins makes that amount, return -1. An amount of 0 needs 0 coins.

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

Explanation: 4 + 4 = 8. Grabbing the largest coin first gives 5 + 1 + 1 + 1, which uses 4 coins.

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

Explanation: Multiples of 3 never reach 4.

Example 3
Input: coins = [2], amount = 0
Output: 0

Constraints

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

Follow-up: How would you count the number of different combinations that make up the amount, instead of the minimum?

💡 Hint 1

Greedy (always take the biggest coin that fits) is wrong for many coin systems, as the first example shows.

💡 Hint 2

Let dp[a] be the fewest coins for amount a. Then dp[a] = 1 + min(dp[a - c]) over every coin c <= a.

💡 Hint 3

Fill dp from 0 up to amount, using a sentinel such as amount + 1 for "unreachable".

/**
 * @param {number[]} coins
 * @param {number} amount
 * @return {number}
 */
function coinChange(coins, amount) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc