Fraction Knapsack
Fractional Knapsack Problem: Greedy Algorithm with Solved Example
In the fractional knapsack problem, we have items of known values and weights, and a knapsack of given capacity. The objective is to fill the knapsack to maximise the profit, but the total weight of the chosen objects cannot exceed the capacity. Unlike the 0/1 knapsack problem, we can break weights into fractional values between zero and one, so fractional values are allowed.
We have:
Items =, Weights =, Values =
If a fraction of the i-th item is selected, then:
Profit Earned
Weight Added to the Knapsack
Thus the total profit earned is:
And the total weight of chosen objects should satisfy:
Mathematical Formulation
Maximize:
Subject to:
the unknown is, which is the solution we want to determine.
Greedy Idea (Optimal)
The greedy strategy is to always select the item with the highest value-to-weight ratio () first. This approach is provably optimal for the fractional knapsack — see Greedy Approach for Algorithm Design.
for p = 1 to n do :
x[i] = 0.0;
u = m; # available capacity
for i = 1 to n do :
{
if (w[i] > u) then break;
x[i] = 1.0;
u = u - w[i];
}
if (i <= n) :
x[i] = u / w[i];
Time Complexity
The complexity of this algorithm is — sorting the items by takes, and the greedy selection loop runs in. So the sorting step dominates. For more on asymptotic complexity, see Asymptotic Notation.
Solved Example: Fractional Knapsack Problem
Capacity of knapsack = 7
Items Data
Item | Weight | Value |
|---|---|---|
1 | 4 | 20 |
2 | 5 | 30 |
3 | 6 | 60 |
1. Initialization
i = 1 to 3 do :
x[i] = 0.0
# x = [0, 0, 0]
2. Finding for All Items
Item (i) | Weight ) | Value ) | |
|---|---|---|---|
1 | 4 | 20 | 5 |
2 | 5 | 30 | 6 |
3 | 6 | 60 | 10 |
3. Arrange in Decreasing Order of
i.e.,
Item (i) | Weight ) | Value ) | |
|---|---|---|---|
1 | 6 | 60 | 10 |
2 | 5 | 30 | 6 |
3 | 4 | 20 | 5 |
4. Greedy Selection
Take Item 1 fully: Weight added = 6. Remaining capacity. Profit = 60.
Next, Item 2 weight = 5 > = 1. Take fraction. Weight added =. Profit =.
Item 3: No capacity left..
5. Total Profit
Related Notes:
