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:
240.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
hrithikrsgupta2 days ago
O(1) space complexity . sort the given array according to value/weight ration using comparator function.
 
class Solution{   public:      static bool comp(Item a, Item b){              return ((double)a.value/a.weight) > ((double)b.value/b.weight);   }      //Function to get the maximum total value in the knapsack.   double fractionalKnapsack(int W, Item arr[], int n)   {              sort(arr,arr+n,comp);        double mx = 0;              for(int i=0;i<n && W>0;i++){                      double perunit = (double)arr[i].value/arr[i].weight;                      if(W>=arr[i].weight){               W -= arr[i].weight;               mx += (perunit*arr[i].weight);           }else{              mx += (perunit*W);               W=0;                         }       }              return mx;          }       };
0
prateekp17293 days ago
class Solution
{   public:   //Function to get the maximum total value in the knapsack.      double fractionalKnapsack(int w, Item arr[], int n)   {       vector<pair<double, int>> ratio(n);       for(int i=0;i<n;i++){           ratio[i].first = (double)(arr[i].value)/(double)arr[i].weight;           ratio[i].second = i;       }       sort(ratio.begin(), ratio.end());       double ans = 0;       for(int i=n-1;i>=0;i--){           if(!w) break;           double weight = arr[ratio[i].second].weight;           double value = arr[ratio[i].second].value;           if(weight<=w){               ans+=value;               w-=weight;           }           else {               ans+=(w/weight)*value;               break;           }       }       return ans;   }       };
0
aloktripathi2563 days ago
//CPP solution
 
double fractionalKnapsack(int W, Item arr[], int n)   {       // Your code here              vector <pair<double ,int>> ratio(n);       for (int i=0;i<n;i++){          ratio[i].first=arr[i].value/(double)arr[i].weight;          ratio[i].second=i;       }       sort(ratio.begin(), ratio.end());       double ans=0;       for (int i=n-1;i>=0;i--){                      if (W==0) break;           else {               if (arr[ratio[i].second].weight <= W) {                   ans+=arr[ratio[i].second].value;                   W=W-arr[ratio[i].second].weight;           }           else {               ans+=(arr[ratio[i].second].value*W/(double)arr[ratio[i].second].weight);               W=0;               }           }       }      return ans;   }
0
mishraswastik02114 days ago

class Frac{
	int p;
	int w;
	double p_w;
	public Frac(int p, int w) {		super();
		this.p = p;
		this.w = w;
		p_w = (double)p/(double)w;
	}
}



class Solution
{
    //Function to get the maximum total value in the knapsack.
    double fractionalKnapsack(int knapsak, Item it[], int n) 
    {
        // Your code here
        
        ArrayList<Frac> a = new ArrayList<Frac>();
		for(int i=0;i<n;i++) {
			a.add(new Frac(it[i].value, it[i].weight));
		}
		
		
		Collections.sort(a,new Comparator<Frac>() {
			@Override
			public int compare(Frac o1,Frac o2) {
				if(o1.p_w == o2.p_w) {
					return 0;					
				}else if(o1.p_w>o2.p_w) {
					return -1;
				}else {
					return 1;
				}
			}
		});
    
        double count = 0;
		for(int i=0;i<n;i++) {
			if(knapsak == 0) {
				break;
			}
			if(knapsak >= a.get(i).w) {
				knapsak -= a.get(i).w;
				count += a.get(i).p;
			}else {
				double val = (double) knapsak/a.get(i).w;
				count += (double)(val*a.get(i).p);
				knapsak = 0;
			}
		}
		return count;
        
    }
}
0
harshbhan261 week ago
bool comparison(Item a,Item b){
        return(((double)a.value/(double)a.weight)>((double)b.value/(double)b.weight));
    }

class Solution
{
    public:
    
    double fractionalKnapsack(int W, Item arr[], int n)
    {
        sort(arr,arr+n,comparison);
        double profit=0;
        for(int i=0;i<n;i++){
            if(W-arr[i].weight>=0){
                W= W-arr[i].weight;
                profit += arr[i].value;
            }
            else{
                profit += W*((double)arr[i].value/(double)arr[i].weight);
                W=0;
                break;
            }
        }
        
        return profit;
    }
        
};
0
harshbhan26
This comment was deleted.
0
2002amit1 week ago
class Solution
{
    public:
    //Function to get the maximum total value in the knapsack.
    double fractionalKnapsack(int W, Item arr[], int n){
        pair<double,int> bag[n];
        for(int i=0;i<n;i++){
            bag[i] = {(double)arr[i].value/arr[i].weight,arr[i].weight};
        }
        sort(bag,bag+n);
        reverse(bag,bag+n);
        double sum = 0;
        for(int i=0;i<n;i++){
            if(W <= 0 && i == n){
                break;
            }
            else if(W > bag[i].second){
                sum += (double)(bag[i].first*bag[i].second);
                W -= bag[i].second;
            }else if( W == bag[i].second){
                W -= bag[i].second;
                sum += (double)(bag[i].first*bag[i].second);
                break;
            }else if(W < bag[i].second){
                sum += (double)(bag[i].first*W);
                break;
            }
        }
        return sum;
    }
        
};
0
mehtameet12341 week ago
// SIMPLE JAVA

// sort item according to the max ratio of value and weight.
// keep adding it to knapsack until the weight becomes 0 (simple cross multiplication to find the last value of profit for fractional weight) and keep adding to the maxProfit

class Solution
{
    double fractionalKnapsack(int W, Item arr[], int n) 
    {
        Arrays.sort(arr, new Comparator<Item>() {
            public int compare (Item a, Item b) {
                double r1 = (double)a.value / (double)a.weight;
                double r2 = (double)b.value / (double)b.weight;
                
                if (r1 < r2) 
                    return 1;
                else
                    return -1;
            }  
        });
        
        double maxProfit = 0;
        int currWeight = W;
        
        for (int i = 0; i < n; i++) {
            if (arr[i].weight <= currWeight) {
                maxProfit += arr[i].value;
                currWeight -= arr[i].weight;
            }
            else {
                maxProfit += (double)currWeight * ((double)arr[i].value / (double)arr[i].weight);
                break;
            }
        }
        
        return maxProfit;
    }
}
0
chandan malpotra1 week ago
    double fractionalKnapsack(int W, Item arr[], int n)   {       vector<pair<double,int>> ratio;       double price=0;       for(int i=0; i<n; i++)       {           double d = arr[i].value/arr[i].weight;           int a = arr[i].weight;           ratio.push_back(make_pair(d,a));        }              sort(ratio.begin(),ratio.end());              for(int i=n-1; i>=0; i--)       {           if(ratio[i].second<=W)           {
               price= price + (ratio[i].first)*(ratio[i].second);                W = W - min(ratio[i].second,W);           }           else           {
               price = price + W*(ratio[i].first);               W = W - min(ratio[i].second,W);               break;           }       }       return price;what's wrong with this code.
+1
upendrasc20012 weeks ago
double fractionalKnapsack(int W, Item arr[], int n)
    {
        // Your code here
        sort(arr,arr+n,[](Item a,Item b){return (a.value*b.weight)>(b.value*a.weight);});
        double ans=0.0;
        for(int i=0;i<n;i++){
            if(arr[i].weight<=W){
                ans+=arr[i].value;
                W-=arr[i].weight;
            }
            else if(arr[i].weight>W){
                ans+=(double)((arr[i].value*W)/(double)arr[i].weight);
                break;
            }
        }
        return ans;
        
    }
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.