Created
Dec 7, 2025
Last Modified
3 months ago

Fraction Knapsack

Fractional Knapsack

In the fractional knapsack problem, we have eight items of known values and weights. The capacity of the knapsack is also given. The objective is to fill the knapsack with these items in order to maximise the profit, but the total weight of the chosen objects cannot be more than the capacity of the knapsack. 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)

powershell
for p = 1 to n do :
    x[i] = 0.0;

u = m; # avaialble 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 simply because of a simple for-loop with a maximum of n iterations. So the algorithm takes linear time to solve the fractional knapsack.


Solve the Given Fractional Knapsack Problem

Capacity of knapsack = 7

Items Data

Item

Weight

Value

1

4

20

2

5

30

3

6

60


1. Initialization

powershell
i = 1 to 3 do :
    x[i] = 0.0

# x = [0, 0, 0]

2. Finding ​ for all items

Item 

Weight 

Value

1

4

20

5

2

5

30

6

3

6

60

10


3. Arrange the table in decreasing order of

i.e.,

Item 

Weight 

Value 

1

6

60

10

2

5

30

6

3

4

20

5

4. Greedy selection

  • Take Item 1 fully:
    Weight added =
    Remaining capacity
    Profit = .

  • Next Item 2
    weight .
    Take fraction .
    Weight added
    Profit .

  • Item 1:
    no capacity left .

5. Calculate the Total