Fractional Knapsack visualization

Take items by best value per weight; split the last one if it does not fully fit.

Because items can be cut, the greedy ratio order is optimal — unlike 0/1 knapsack, where it can fail.

Edge cases: capacity 0 takes nothing; zero-weight items have infinite ratio and are always taken whole; everything fitting means no fraction is needed.

Complexity

Time: best O(n log n), average O(n log n), worst O(n log n). Space: O(n). Difficulty: Beginner.

Pseudocode

procedure fractionalKnapsack(items, W):
  sort items by value/weight descending
  total ← 0
  for (w, v) in items:
    if W = 0: break
    take ← min(w, W)
    total ← total + v · take / w; W ← W − take
  return total

More greedy algorithms