# Fractional Knapsack Problem

Data StructureGreedy AlgorithmAlgorithms

A list of items is given, each item has its own value and weight. Items can be placed in a knapsack whose maximum weight limit is W. The problem is to find the weight that is less than or equal to W, and value is maximized.

There are two types of Knapsack problem.

• 0 – 1 Knapsack
• Fractional Knapsack

For the 0 – 1 Knapsack, items cannot be divided into smaller pieces, and for fractional knapsack, items can be broken into smaller pieces.

Here we will discuss the fractional knapsack problem.

The time complexity of this algorithm is O(n Log n).

## Input and Output

Input:
Maximum weight = 50. List of items with value and weight.
{(60, 10), (100, 20), (120, 30)}
Output:
Maximum value: 240
By taking the items of weight 20 and 30

## Algorithm

fractionalKnapsack(weight, itemList, n)

Input − maximum weight of the knapsack, list of items and the number of items

Output: The maximum value obtained.

Begin
sort the item list based on the ration of value and weight
currentWeight := 0
knapsackVal := 0

for all items i in the list do
if currentWeight + weight of item[i] < weight then
currentWeight := currentWeight + weight of item[i]
knapsackVal := knapsackVal + value of item[i]
else
remaining := weight – currentWeight
knapsackVal “= knapsackVal + value of item[i] * (remaining/weight of item[i])
break the loop
done
End

## EXample

#include <iostream>
#include<algorithm>
using namespace std;

struct item {
int value, weight;
};

bool cmp(struct item a, struct item b) {     //compare item a and item b based on the ration of value and weight
double aRatio = (double)a.value / a.weight;
double bRatio = (double)b.value / b.weight;
return aRatio > bRatio;
}

double fractionalKnapsack(int weight, item itemList[], int n) {
sort(itemList, itemList + n, cmp);      //sort item list using compare function
int currWeight = 0;        // Current weight in knapsack
double knapsackVal = 0.0;

for (int i = 0; i < n; i++) {       //check through all items
if (currWeight + itemList[i].weight <= weight) {     //when the space is enough for selected item, add it
currWeight += itemList[i].weight;
knapsackVal += itemList[i].value;

}else{       //when no place for whole item, break it into smaller parts
int remaining = weight - currWeight;
knapsackVal += itemList[i].value * ((double) remaining / itemList[i].weight);
break;
}
}
return knapsackVal;
}

int main() {
int weight = 50;     // Weight of knapsack
item itemList[] = {{60, 10}, {100, 20}, {120, 30}};
int n = 3;
cout << "Maximum value: " << fractionalKnapsack(weight, itemList, n);
}

## Output

Maximum value: 240