Fill a knapsack with items you can slice — gold bars you can cut, grain you can scoop, bandwidth you can split.
Because every item is infinitely divisible, you never face painful either/or decisions: take the best item, and if the bag runs low, take part of the next best. That makes the greedy rule — take the best value-per-weight first — not just good, but provably optimal.
How It Works
- Compute the value-per-weight ratio for every item.
- Sort items by ratio, descending.
- Take items in that order, filling the knapsack completely.
- If the next item would overflow, take only the fraction that fits.
take full items by ratio; on overflow, take (remaining capacity / weight) of the next item
Key Insight
The natural unit of comparison is value per unit weight — that’s what the greedy measures.
Divisibility is what makes the strategy airtight: there’s no hidden “combination” to discover, because any unused capacity can always be filled by a fraction of the next-best item.
This is exactly why the same greedy fails for 0/1 Knapsack, where indivisibility forces choices that greedy can’t undo.
Worked Example
The visualizer packs capacity 50 with three items:
| Item | Weight | Value | Ratio (v/w) |
|---|---|---|---|
| Gold | 10 | 60 | 6.0 |
| Silver | 20 | 100 | 5.0 |
| Bronze | 30 | 120 | 4.0 |
- Take all Gold (10w → 60), then all Silver (20w → 100): 30w used, value 160.
- Remaining capacity 20 of Bronze: take ²⁄₃ of Bronze → 80.
- Total value = 240 — the visualizer’s final answer.
Notice how the last item is partial. If these items were indivisible (0/1), this exact greedy would fail — it would waste the 20 leftover and you’d instead want a clever combination.
Edge Cases & Pitfalls
- Ties in ratio — order among equal ratios doesn’t affect the total.
- Zero-value items — ratio 0: never worth taking.
- Zero-weight items — avoid division by zero; they contribute infinite ratio and are usually excluded.
- Capacity ≥ total weight — take everything: no fraction needed.
- Indivisible items — greedy is not optimal: use 0/1 Knapsack DP instead.
Comparison: Fractional vs 0/1 Knapsack
| Aspect | Fractional | 0/1 |
|---|---|---|
| Items divisible | Yes | No |
| Greedy optimal? | Yes | No |
| Complexity | O(n log n) | O(nW) |
| Objective | Fill by best ratio | Choose subset |
Applications
- Bulk cargo — hauling divisible goods (fuel, grain, ore)
- Time budgeting — allocating hours to tasks by value/hour
- Network bandwidth — proportional resource sharing
Practice Trajectory
- Hand-compute the ratios for the visualizer’s three items and reproduce the fill order.
- Confirm the ²⁄₃ Bronze cut: why 20 units, and why value 80?
- Change capacity to 100 and recompute — no fraction is needed.
- Make Gold indivisible and find a counterexample where greedy fails.
- Explain in one sentence why divisibility is the crux of greedy’s optimality here.