
#Fractional knapsack code#
Which will always be the optimal solution to this problem.Ī simple code with our own comparison function can be written as follows, please see sort function more closely, the third argument to sort function is our comparison function which sorts the item according to value/weight ratio in non-decreasing order.Īfter sorting we need to loop over these items and add them in our knapsack satisfying above-mentioned criteria. We have to follow the below given steps to solve the fractional Knapsack Problem: Similar to the 0-1 Knapsack Problem, we will be given weights and values of n items, in this case, six items. 0/1-Knapsack is a well known problem where, it is desired to get the maximum total profit by placing n items (each item is having some weight and associated profit) into a knapsack of capacity W. We can even put the fraction of any item into the knapsack if taking the complete item is not possible. 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. In Fractional Knapsack Problem, As the name suggests, items are divisible here.

the GREEDY CHOICE looks good at the moment, and it is globally. 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. GREEDY CHOICE: can make the DECISION without.

Input :Ī brute-force solution would be to try all possible subset with all different fraction but that will be too much time taking.Īn efficient solution is to use Greedy approach. Fractional Knapsack Problem: Same as before but we are allowed to take fractions of items ( gold dust). This problem in which we can break an item is also called the fractional knapsack problem.

In Fractional Knapsack, we can break items for maximizing the total value of knapsack.
