In Fractional Knapsack, we can break items for maximizing the total value of knapsack. This problem in which we can break an item is also called the fractional knapsack problem.
Same as above
Maximum possible value = 240
By taking full items of 10 kg, 20 kg and
2/3rd of last item of 30 kg
A brute-force solution would be to try all possible subsets with all different fractions but that will be too much time taking.
An efficient solution is to use the Greedy approach. The basic idea of the greedy approach is to calculate the ratio value/weight for each item and sort the item on basis of this ratio. Then take the item with the highest ratio and add them until we can’t add the next item as a whole and at the end add the next item as much as we can. Which will always be the optimal solution to this problem.
Calculate the ratio(value/weight) for each item.
Sort all the items in decreasing order of the ratio.
Initialize res =0, curr_cap = given_cap.
Do the following for every item “i” in the sorted order:
A simple code with our own comparison function can be written as follows, please see the sort function more closely, the third argument to the sort function is our comparison function which sorts the item according to value/weight ratio in non-decreasing order. After sorting we need to loop over these items and add them to our knapsack satisfying the above-mentioned criteria.
Below is the implementation of the above idea:
// C/C++ program to solve fractional Knapsack Problem
// Structure for an item which stores weight and
// corresponding value of Item
this->value = value;
this->weight = weight;
// Comparison function to sort Item according to val/weight