Fractional Knapsack
Fractional Knapsack is a GFG problem (Easy). You get n items, where item i is worth val[i] and weighs wt[i], and a knapsack that holds at most capacity weight.
- You may put part of an item in the knapsack. Taking a fraction
fof itemiaddsf × val[i]value andf × wt[i]weight. - Return the largest total value the knapsack can hold. It is usually not a whole number.
With up to 10⁵ items, the solution should run in about O(n log n).
- 1 <= val.size() = wt.size() <= 10⁵
- 1 <= val[i], wt[i] <= 10⁴
- 1 <= capacity <= 10⁹
- Any fraction of an item may be taken
Intuition
Give every item a score, its value per unit of weight (val[i] / wt[i]), and fill the knapsack greedily from the highest score down, cutting only the item that does not fit.
Why is that order safe? Suppose a packing holds some weight of a low-score item while a higher-score item is not fully packed. Swap one unit of the low-score item for one unit of the higher one: the weight stays the same and the value goes up. So the best packing never leaves a higher-score item unfinished while a lower one is inside, which is exactly the order the greedy fills in.
"Spend a fixed budget on goods that can be split" is this problem: loading fuel of different grades, buying spices by the gram, filling a link with traffic of different worth. The words to look for are a single limit and goods that can be divided.
Approach
Before reading on, find the one number that lets you compare a heavy, valuable item with a light, cheap one. Then decide what to do with the first item that does not fit. Aim for O(n log n).
Sort the items by value per unit of weight
Pair each value with its weight and sort the pairs by val / wt, largest first. After this, the item that pays the most for each unit of space is always next, so the rest is a single pass from left to right.
Take whole items while they fit
Walk the sorted list. While an item's full weight is at most the space left, add its whole value and subtract its weight from capacity. Every item taken this way pays more per unit than anything later in the list.
Cut the first item that does not fit
When an item is heavier than the space left, take the fraction capacity / wt of it, which adds val × capacity / wt. That fraction fills the knapsack exactly, so stop the loop: no space is left for anything else.
Return the total
If the loop ends without a cut, every item fit and the answer is the sum of all values. Either way, return the total as a decimal number, since a cut item usually leaves a fraction.
Code in Python, C++ and Java
Common pitfalls
Sorting by value instead of value per weight
items = sorted(zip(val, wt), reverse=True)
items = sorted(zip(val, wt), key=lambda it: it[0] / it[1], reverse=True)
Sorting the pairs directly orders them by value. For val = [60, 100, 120], wt = [10, 20, 30], capacity 50, that takes 120 and 100 whole and returns 220. The light item worth 6 per unit never gets in, yet the right answer is 240.
Skipping the item that does not fit
if w <= capacity:
total += v
capacity -= w
else:
continueelse:
total += v * capacity / w
breakThis treats items as all-or-nothing. On the same input it takes 60 and 100, skips 120, and returns 160: twenty units of space stay empty that two thirds of the last item could have filled.
Floor division in the cut
total += v * capacity // w
total += v * capacity / w
// throws away the decimals. For val = [500], wt = [30], capacity 10, the answer is 166.67, but floor division returns 166. In C++ and Java, cast to double before dividing for the same reason.
Complexity
Fractional vs 0/1 knapsack
Both ask for the most value under a weight limit. The only difference is whether an item can be split, and that one rule changes the method.
| Problem | Items | Method | val [60, 100, 120], wt [10, 20, 30], capacity 50 |
|---|---|---|---|
| Fractional knapsack (this page) | can be split | greedy by value per weight, O(n log n) | 240: 60 + 100 + two thirds of 120 |
| 0/1 knapsack | whole or nothing | dynamic programming over capacity, O(n · W) | 220: 100 + 120. Greedy by value per weight gets only 160 here, because it cannot cut the last item. |
Fractional Knapsack FAQ
Can it be solved without sorting?
Yes, in expected O(n). Pick a random ratio as a pivot, as quickselect does, and add up the weight of the items above it. If they fit, take them all and search the lower part; if not, search the upper part. Only the one item that gets cut has to be found, not the full order. Interviews rarely ask for it.