function greedyCoinChange(coins, amount) {
const result = [];
for (const coin of coins) {
while (amount >= coin) {
amount -= coin;
result.push(coin);
}
}
return result;
}
console.log(greedyCoinChange([25, 10, 5, 1], 30));The greedy algorithm picks the largest coin less than or equal to the remaining amount. For 30 cents, it picks 25 first, then 5. So the output is [25, 5].
function greedyCoinChange(coins, amount) {
const result = [];
for (const coin of coins) {
while (amount >= coin) {
amount -= coin;
result.push(coin);
}
}
return result;
}
console.log(greedyCoinChange([4, 3, 1], 6));The greedy algorithm picks 4 first, then two 1s to make 6. But the optimal solution is two 3s. This shows greedy can fail to find the best solution.
Choosing the earliest finishing activity leaves the most time for other activities, ensuring maximum number of non-overlapping activities can be selected.
function fractionalKnapsack(weights, values, capacity) {
const items = weights.map((w, i) => ({weight: w, value: values[i], ratio: values[i] / w}));
items.sort((a, b) => b.ratio - a.ratio);
let totalValue = 0;
let remaining = capacity;
for (const item of items) {
if (item.weight <= remaining) {
totalValue += item.value;
remaining -= item.weight;
} else {
totalValue += item.ratio * remaining;
break;
}
}
return totalValue;
}
console.log(fractionalKnapsack([10, 20, 30], [60, 100, 120], 50));The items sorted by ratio are: (60/10=6), (100/20=5), (120/30=4). Take all of first two items (weight 30, value 160), then 20 weight from last item (fraction), value 80. Total 240.
Greedy fails for coin change with arbitrary denominations because it may pick larger coins first and miss the minimal coin count solution.
