Fractional Knapsack | Practice | GeeksforGeeks

Given weights and values of N items, we need to put these items in a knapsack of capacity W to get the maximum total value in the knapsack.
Note: Unlike 0/1 knapsack, you are allowed to break the item. 
 
Example 1:
Input:
N = 3, W = 50
values[] = {60,100,120}
weight[] = {10,20,30}
Output:
220.00
Explanation:Total maximum value of item
we can have is 240.00 from the given
capacity of sack. 

Example 2:
Input:
N = 2, W = 50
values[] = {60,100}
weight[] = {10,20}
Output:
160.00
Explanation:
Total maximum value of item
we can have is 160.00 from the given
capacity of sack.
 
Your Task :
Complete the function fractionalKnapsack() that receives maximum capacity , array of structure/class and size n and returns a double value representing the maximum value in knapsack.
Note: The details of structure/class is defined in the comments above the given function.

Expected Time Complexity : O(NlogN)
Expected Auxilliary Space: O(1)

Constraints:
1 <= N <= 105
1 <= W <= 105
0
sikkusaurav123in 8 hours
This is correct but somewhere floating point mistake if someone find it please tag that thing :
class Solution{   public:   //Function to get the maximum total value in the knapsack.   double fractionalKnapsack(int W, Item arr[], int n)   {       // Your code here       vector<pair<float,int>>v;       float profit=0.00;       for(int i=0;i<n;i++)       {           v.push_back(make_pair((float(arr[i].value)/float(arr[i].weight)),i));       }       sort(v.begin(),v.end());       reverse(v.begin(),v.end());       for(int i=0;i<n;i++)       {           if(W>0 && W>arr[v[i].second].weight)           {               profit=profit+float(arr[v[i].second].value);               W=W-arr[v[i].second].weight;           }           else if(W>0 && W<arr[v[i].second].weight)           {               profit=profit+(float(arr[v[i].second].value)*float(float(W)/float(arr[v[i].second].weight)));               W=W-arr[v[i].second].weight;           }           else if(W<=0)       {           break;       }              }       return (profit);             }       };
 
0
19003001002372 days ago
class Solution{   public:   static bool comp(Item a, Item b) {       double r = (double)a.value/(double)a.weight;       double r1 = (double)b.value/(double)b.weight;       return r > r1;   }   //Function to get the maximum total value in the knapsack.   double fractionalKnapsack(int W, Item arr[], int n)   {       // Your code here       sort(arr,arr+n,comp);       int cur_w = 0;       double profit = 0.0;       for(int i =0;i<n;i++) {           if(cur_w + arr[i].weight <= W) {               profit += arr[i].value;               cur_w += arr[i].weight;           }           else {               int remain = W - cur_w;               profit += (double)remain/(double)arr[i].weight * arr[i].value;               break;           }       }       return profit;   }       };
0
akshatjain232 days ago
/*
class Item {
    int value, weight;
    Item(int x, int y){
        this.value = x;
        this.weight = y;
    }
}
*/

class Solution
{
    //Function to get the maximum total value in the knapsack.
    double fractionalKnapsack(int W, Item arr[], int n) 
    {
        /* Sort the items in the descreasing order of 
        there value per weight */
        Arrays.sort(arr, new ItemComparator());
        
        double max = 0;
        
        for(Item item : arr) {
            
            // If remaining capacity is 0, knapsack is full
            if( W == 0 ) break;
            
            /* If current item's weight not more than the capacity
            then include the item in the knapsack */
            if( item.weight <= W ) {
                max += item.value;
                W -= item.weight;
            } else {
                /* Else store the fraction of the item updating remaining 
                capacity */
                max += (double)(item.value*W) / item.weight;
                W = 0;
            }
        }
        
        return max;
    }
}
class ItemComparator implements Comparator<Item> {
    @Override
    public int compare(Item item1, Item item2) {
        double valuePerWeight1 = (double)item1.value / item1.weight;
        double valuePerWeight2 = (double)item2.value / item2.weight;
        
        if( valuePerWeight2 > valuePerWeight1 ) {
            return 1;
        } else if( valuePerWeight2 < valuePerWeight1  ) {
            return -1;
        } 
        return 0;
    }
}
+1
ksbsbisht1371 week ago
static bool cmp(struct Item a,struct Item b) {       double r1=(double)a.value/(double)a.weight;       double r2=(double)b.value/(double)b.weight;       if(r1<r2) return false;       return true;   }   double fractionalKnapsack(int W, Item arr[], int n) {       sort(arr,arr+n,cmp);       double cost=0;       for(int i=0;i<n;i++) {           if(arr[i].weight<=W) {               W-=arr[i].weight;               cost+=arr[i].value;           } else {                   cost+=((double)arr[i].value/(double)arr[i].weight)*W;                   break;               }       }       return cost;   }
0
ksbsbisht1371 week ago
double fractionalKnapsack(int W, Item arr[], int n) {       vector<pair<double,pair<int,int>>> vec;       for(int i=0;i<n;i++) {           vec.push_back({arr[i].value/(arr[i].weight*1.0),{arr[i].value,arr[i].weight}});       }       sort(vec.begin(),vec.end(),greater<pair<double,pair<int,int>>> ());       double cost=0.0;       for(int i=0;i<n;i++) {           if(vec[i].second.second<=W) {               W-=vec[i].second.second;               cost+=vec[i].second.first;           } else {               if(W>0) {                   cost+=W*vec[i].first;                   break;               }           }       } return cost;   }
0
manasbass992 weeks ago
def fractionalknapsack(self, W,Items,n):
        # code here
        res = 0.0
        Items.sort(key=lambda x: -x.value/x.weight)
        for item in Items:
            if W >= item.weight:
                W -= item.weight
                res += item.value
            elif W > 0 and W<item.weight:
                res += item.value * W/item.weight
                W = 0
            if W == 0:
                break
        return res
0
ponkey
This comment was deleted.
0
dadwalabhishek101 month ago
//You dont have to sort the values and put the complexity in nlogn and space comp O(N). Just use max heap and find out the value
class Solution
{
    public:
    //Function to get the maximum total value in the knapsack.
    double fractionalKnapsack(int W, Item arr[], int n)
    {
        // Your code here
        double ans = 0.0;
        priority_queue<pair<double, int>> pq;
        for(int i = 0;i<n;i++)
        {
            pq.push({(double)arr[i].value/(double)arr[i].weight, arr[i].weight});
        }
        while(!pq.empty())
        {
            if(W==0) return ans;
            int diff = min(pq.top().second, W);
            ans += diff*pq.top().first;
            W -= diff;
            pq.pop();
        }
        return ans;
    }
        
};

-1
gaurabhkumarjha271020011 month ago
// easy c++ approach
static bool comp (pair <double,double> a, pair<double,double> b){
         
      double r= a.first / a.second;
      double r1= b.first/b.second;
      return r > r1;
     }
    double fractionalKnapsack(int W, Item arr[], int n)
    {
      vector <pair <double,double> > v;
     double res=0.0;
        
        for (int i=0; i< n; i++){
            
        v.push_back ({arr[i].value, arr[i].weight});
      }
      sort (v.begin(), v.end(), comp);
      for (int i=0; i< n; i++){
            
      if (v[i].second <= W){ // first means value 
          res+= v[i].first; // second means weight
          W-=   v[i].second;
      }else{
           if (W != 0) 
           res+= (W* (v[i].first/v[i].second));
           W=0;
           break;
        }
      } 
       return res;
    }
-1
badgujarsachin832 months ago
 static bool com(Item a,Item b){
        double a1=(double)a.value/a.weight;
        double a2=(double)b.value/b.weight;
        return a1>a2;
    }
    //Function to get the maximum total value in the knapsack.
    double fractionalKnapsack(int W, Item arr[], int n)
    {
        // Your code here
        sort(arr,arr+n,com);
        double sum=0;
        for(int i=0;i<n;i++){
            if(arr[i].weight<W){
                sum+=(double)arr[i].value;
                W-=arr[i].weight;
            }else{
                sum+=(double)arr[i].value*(double)W/(double)arr[i].weight;
                break;
            }
        }
        return sum;
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.