Fractional Knapsack Problem
Fractional Knapsack Problem
to fill a knapsack with items so that the total value of the items in the knapsack is maximized.
Problem Statement: The weight of N items and their corresponding values are given. We
have to put these items in a knapsack of weight W such that the total value obtained is
maximized. The point is that we can take fractional amounts of each item, so an item doesn’t
have to be “all or nothing”.
The fractional knapsack problem is applied in many different fields. For example, in logistics,
it can be used to determine the most efficient way to load a truck with a given set of items. In
finance, it can be used to choose which investments to make in order to maximize return while
staying within a budget.
Steps
Fractional knapsack problem is solved using greedy method in the following steps-
1. Sort the array in decreasing order using the value/weight ratio.
2. Start taking the element having the maximum value/weight ratio.
3. If the weight of the current item is less than the current knapsack capacity, add the whole
item, or else add the portion of the item to the knapsack.
4. Stop adding the elements when the capacity of the knapsack becomes 0
5. Now we will have the maximum possible value in a knapsack.
For the given set of items and knapsack capacity = 60 kg, find the optimal solution for the
fractional knapsack problem making use of greedy approach.
Item Weight Value
1 5 30
2 10 40
3 15 45
4 22 77
5 25 90
Solution
Compute the value / weight ratio for each item
Items Weight Value Ratio
1 5 30 6
2 10 40 4
3 15 45 3
4 22 77 3.5
5 25 90 3.6
Start filling the knapsack by putting the items into it one by one.
• The knapsack will be filled if we put 20 Kg in it, but weight of Item-4 is 22 kg.
• In fractional knapsack problem, the fraction of any item can be taken.
20
• So, part of Item-4 will be taken in the knapsack.
22
• So, finally the knapsack will contain the following items:
✓ Item-1
✓ Item-2
✓ Item-5
20
✓ part of Item-4
22
20
Hence, cost of the knapsack is 160+, *77 = 160+70=230
22
Time Complexity: O (n log n + n). O (n log n) to sort the items and O(n) to iterate through
all the items for calculating the answer.