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
- Unlike the 0/1 knapsack, you may take a fraction of an item.
- Compute value ÷ weight for each item. That is how much value each kilogram brings.
- Take items from the best ratio downward. If one does not fit whole, take just the fraction that fills the bag.
- This greedy is optimal for the fractional version (but not for 0/1). O(n log n).
Watch it run
Loading animation…