1. Sort by ratio
Take the most value-dense items first.
items.sort((a, b) => b.value / b.weight - a.value / a.weight)Typorithm · medium
Step 1 of 8 · intro card
Greedy
Sort items by value-to-weight ratio, take whole items greedily, then a fraction of the next to fill up.
Unlike 0/1 knapsack, you may take fractions of an item.
The greedy choice is to always take the most value-dense item available.
When the next item does not fully fit, take just enough of it to fill the remaining capacity.
Sort by value / weight, descending.
Take whole items while they fit.
Fill the last gap with a fraction.
function fractionalKnapsack(items, capacity) {
items.sort((a, b) => b.value / b.weight - a.value / a.weight);
let total = 0;
for (const { value, weight } of items) {
if (capacity >= weight) {
total += value;
capacity -= weight;
} else {
total += value * (capacity / weight);
break;
}
}
return total;
}Connect each part of the code to the concept before you type.
Take the most value-dense items first.
items.sort((a, b) => b.value / b.weight - a.value / a.weight)If the item fits, take all of it.
if (capacity >= weight)Otherwise take the fraction that fills the remaining capacity.
total += value * (capacity / weight)After a partial item the knapsack is full, so stop.
breakRead the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputCapacity 50 · items [{"value":60,"weight":10},{"value":100,"weight":20},{"value":120,"weight":30}]
Follow temporary values, local state and supporting structures at this step.
No temporary values have been saved in this frame yet.
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state