Fractional knapsack

Most value per kilo · Part of Strategies

Key idea

Practice

6 questions · about 3 min

Explained step by step

Fractional knapsack

The fractional knapsack is like the 0-1: n items with weight and value, and a capacity. Each item is chosen once, but you can take just a part of it, and earn the matching share of its value. If a 4 kg cheese is worth $12 and 1 kg is free, you take 1 kg and add $3. That changes everything: dynamic programming is no longer needed and a greedy is enough.

The key is the value per kilo: val[i − 1] ÷ wgt[i − 1]. If you take a piece of w kilos, it adds w × val[i − 1] ÷ wgt[i − 1]. For example: A weighs 2 and is worth 10, 5 per kilo; B weighs 3 and is worth 18, 6 per kilo; C weighs 4 and is worth 12, 3 per kilo. To get the most from each kilo of knapsack, B is best, then A and then C.

There is a way to see it with a drawing. Each item is a bar: its width is its weight and its height, its value per kilo. The bar's area is its value. Filling the knapsack is covering a fixed width, the capacity, with as much area as possible. If the tallest bars go first, each unit of width gets the greatest height available. With capacity 6: 3 wide at height 6, 2 at height 5 and 1 at height 3, area 18 + 10 + 3 = 31.

Greedy algorithm

To get the highest value, each kilo of knapsack must be worth as much as possible. The greedy strategy: sort the items from highest to lowest value per kilo, walk them taking whole the ones that fit, and when one does not fit, take just enough to fill the knapsack. Then stop. With capacity 6: all of B (3 kg, 18), all of A (2 kg, 10) and 1 kg of C (3): 31 in total.

Time complexity

Sorting the items with the language's sort costs O(n log n) time and O(log n) or O(n) memory. Then, in the worst case, the whole list is walked: O(n). Since a list of Item objects with weight and value is created, memory is O(n). The total time is O(n log n), because of the sort: with 1,000 items, about 10,000 steps.

Greedy-choice property

The proof is by contradiction. Suppose item x has the highest value per kilo and there is an optimal solution, worth res, that does not use all of it. If 1 kg of any other item is removed and 1 kg of x is put in, the value goes up, because x is worth more per kilo. So res was not optimal: contradiction. The optimum therefore always uses the highest value per kilo first.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

Most value per kilo