Skip to problem
←

Coin Change

Medium 0 attempts

You have an unlimited supply of coins in the denominations given by array coins, and need to make up a target amount. Find the smallest number of coins that sum exactly to amount, or return -1 if no combination of the given coins can reach it.

Function contract

Implement coinChange(coins, amount), where coins contains positive denominations and amount is a non-negative integer. Each denomination can be reused without limit.

Output: The fewest coins summing exactly to amount; -1 if impossible; 0 when amount is zero.

Example 1

Input
coins = [1,2,5]
amount = 11
Output
3

Example 2

Input
coins = [2]
amount = 3
Output
-1

Example 3

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

Bottom-Up DP

dp[i] = minimum coins for amount i.

javascript
function coinChange(coins, amount) {
  const dp = Array(amount + 1).fill(amount + 1);
  dp[0] = 0;
  for (let i = 1; i <= amount; i++) {
    for (const c of coins) {
      if (c <= i) dp[i] = Math.min(dp[i], dp[i - c] + 1);
    }
  }
  return dp[amount] > amount ? -1 : dp[amount];
}

Time: O(amount × coins) | Space: O(amount)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript