GeeksforGeeks Easy

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 f of item i adds f × val[i] value and f × 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).

Constraints
  • 1 <= val.size() = wt.size() <= 10⁵
  • 1 <= val[i], wt[i] <= 10⁴
  • 1 <= capacity <= 10⁹
  • Any fraction of an item may be taken
greedysorting
Open on GeeksforGeeks ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def fractionalKnapsack(self, val, wt, capacity):
▶3 items = sorted(zip(val, wt), key=lambda it: it[0] / it[1], reverse=True)
▶4 total = 0.0
▶5 for v, w in items:
▶6 if w <= capacity:
▶7 total += v
▶8 capacity -= w
▶9 else:
▶10 total += v * capacity / w
▶11 break
▶12 return total
items as given60weight 106 per unit100weight 205 per unit120weight 304 per unitknapsack, capacity 50empty0 of 50 usedtotal0score each item: value ÷ weight
capacity50
items3
Each item's score is its value per unit of weight, written under it. It says how much one unit of knapsack space earns if it is spent on that item, which is the only fair way to compare a heavy item with a light one.
items, best value per unit first60weight 106 per unit100weight 205 per unit120weight 304 per unitknapsack, capacity 50empty0 of 50 usedtotal0sorted: best value per unit first
order60, 100, 120by value per unit
Sort by that score, highest first. From here on, the next item always pays at least as much per unit as anything after it, so the knapsack is filled from left to right without ever looking back.
items, best value per unit first60weight 106 per unit100weight 205 per unit120weight 304 per unitknapsack, capacity 5060empty10 of 50 usedtotal60weight 10 fits in 50 → take all of 60
space left4050 − 10
total60
The item worth 60 weighs 10 and 50 units are free, so it goes in whole. Nothing later in the list pays more per unit, so there is no reason to hold space back for it.
items, best value per unit first60weight 106 per unit100weight 205 per unit120weight 304 per unitknapsack, capacity 5060100empty30 of 50 usedtotal60+100=160weight 20 fits in 40 → take all of 100
space left2040 − 20
total160
The item worth 100 weighs 20 and 40 units are free, so it goes in whole. Nothing later in the list pays more per unit, so there is no reason to hold space back for it.
items, best value per unit first60weight 106 per unit100weight 205 per unit120weight 304 per unitknapsack, capacity 50601008050 of 50 usedtotal60+100+80=240weight 30 > 20 left → take 2/3 of it, worth 80
fraction2/320 of 30 units
adds80120 × 20 ÷ 30
The item worth 120 weighs 30 but only 20 units are free. Splitting is allowed, so take 2/3 of it, worth 80. The knapsack is now exactly full.
items, best value per unit first60weight 106 per unit100weight 205 per unit120weight 304 per unitknapsack, capacity 50601008050 of 50 usedtotal60+100+80=240knapsack full → answer 240
answer240
used50 of 50
The answer is 240. Every item was used, the last one only in part, and not one unit of space is wasted.
05

Common pitfalls

Sorting by value instead of value per weight

✗ Wrong
items = sorted(zip(val, wt), reverse=True)
✓ Right
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

✗ Wrong
if w <= capacity:
    total += v
    capacity -= w
else:
    continue
✓ Right
else:
    total += v * capacity / w
    break

This 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

✗ Wrong
total += v * capacity // w
✓ Right
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.

06

Complexity

Time
O(n log n)
Space
O(n)
The algorithm spends O(n log n) sorting the n pairs and O(n) on the walk. The sorted copy of the pairs takes O(n) space.
07

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.

ProblemItemsMethodval [60, 100, 120], wt [10, 20, 30], capacity 50
Fractional knapsack (this page)can be splitgreedy by value per weight, O(n log n)240: 60 + 100 + two thirds of 120
0/1 knapsackwhole or nothingdynamic 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.
08

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.