☰ All problems

Coin Change

A vending machine has to pay out exactly amount cents in change. It holds an unlimited supply of coins of every denomination in coins, and to keep any one coin tube from running empty, it wants to pay with as few coins as possible.

Return the smallest number of coins that add up to exactly amount. If no combination of the available denominations reaches that amount, return -1. Paying out 0 cents takes 0 coins.

Example 1
Input: coins = [1,6,10], amount = 12
Output: 2

Explanation: 6 + 6 uses two coins. Taking the largest coin first gives 10 + 1 + 1, which uses three.

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

Explanation: Every coin is even, so no combination can reach an odd amount.

Example 3
Input: coins = [2,5], amount = 11
Output: 4

Explanation: 5 + 2 + 2 + 2. Using two 5s would leave 1, which no coin can pay.

Constraints

  • There are between 1 and 12 denominations.
  • Each denomination is between 1 and 2^31 - 1 cents.
  • amount is between 0 and 10^4.

Follow-up: Instead of the fewest coins, how would you count how many different combinations of coins pay out the amount?

💡 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