function minCoins(coins: number[], amount: number): number {
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] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}
console.log(minCoins([1, 2, 5], 11));The minimum coins to make 11 using [1, 2, 5] are 3 coins: 5 + 5 + 1.
function minCoins(coins: number[], amount: number): number {
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] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}
console.log(minCoins([2, 4], 3));Amount 3 cannot be formed using coins 2 and 4, so the function returns -1.
function minCoins(coins: number[], amount: number): number {
const dp = new Array(amount + 1).fill(0);
for (let i = 1; i <= amount; i++) {
dp[i] = Infinity;
for (const coin of coins) {
if (coin <= i) {
dp[i] = Math.min(dp[i], dp[i - coin] + 1);
}
}
}
return dp[amount] === Infinity ? -1 : dp[amount];
}
console.log(minCoins([1, 3, 4], 6));The dp array is initialized with zeros, so dp[0] = 0 but other dp[i] are also zero initially, which is incorrect. They should be initialized to Infinity except dp[0].
The algorithm uses two nested loops: one over the amount (m) and one over the coins (n), resulting in O(n * m) time complexity.
Using coin 3 once, the remaining amount is 3. Minimum coins for 3 using 1 and 4 is 3 (1+1+1). Total coins = 1 + 3 = 4 is wrong. But better is using 4 once and 1 twice: 4 + 1 + 1 = 6 with 3 coins total. Since coin 3 can be used once, best is 3 coins.
