Skip to content
StackDecode
GreedyAnimated

Fractional Knapsack

Take items by best value per weight, splitting the last one.

Time

O(n log n)

Extra space

O(1)

Use it for

Divisible resources.

How it works

  1. Unlike the 0/1 knapsack, you may take a fraction of an item.
  2. Compute value ÷ weight for each item. That is how much value each kilogram brings.
  3. Take items from the best ratio downward. If one does not fit whole, take just the fraction that fills the bag.
  4. This greedy is optimal for the fractional version (but not for 0/1). O(n log n).

Watch it run

Loading animation…