Overview
Given an array of coin denominations and a target amount, return the fewest number of coins needed to make up that amount. If the amount cannot be made up by any combination of the given coins, return -1.
You have an infinite supply of each coin denomination.
Constraints
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10,000- Each coin denomination is a positive integer.
- Coins array may not be sorted.
Examples
minCoins([1, 5, 10, 25], 36); // => 3 (25 + 10 + 1)
minCoins([2], 3); // => -1 (impossible with only 2-cent coins) minCoins([1], 0); // => 0 (no coins needed for amount 0)
Solution
Reveal solution
function minCoins(coins, amount) {
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (let i = 1; i <= amount; i++) {
for (const coin of coins) {
if (coin <= i && dp[i - coin] + 1 < dp[i]) {
dp[i] = dp[i - coin] + 1;
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}Classic bottom-up DP. For each amount i, try subtracting each coin and take the minimum.
Resources
minimum-coins-for-change.js
Minimum Coins for Change
mediumcodingAlgorithmsDynamic Programming
Overview
Given an array of coin denominations and a target amount, return the fewest number of coins needed to make up that amount. If the amount cannot be made up by any combination of the given coins, return -1.
You have an infinite supply of each coin denomination.
Constraints
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10,000- Each coin denomination is a positive integer.
- Coins array may not be sorted.
Examples
minCoins([1, 5, 10, 25], 36); // => 3 (25 + 10 + 1)
minCoins([2], 3); // => -1 (impossible with only 2-cent coins) minCoins([1], 0); // => 0 (no coins needed for amount 0)
Solution
Reveal solution
function minCoins(coins, amount) {
const dp = new Array(amount + 1).fill(Infinity);
dp[0] = 0;
for (let i = 1; i <= amount; i++) {
for (const coin of coins) {
if (coin <= i && dp[i - coin] + 1 < dp[i]) {
dp[i] = dp[i - coin] + 1;
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}Classic bottom-up DP. For each amount i, try subtracting each coin and take the minimum.
Resources
NameTopicDifficulty
103 of 103 problems