the below code is for fractional knapsnack problem , I have tried this using pair , but it seems some of the test cases are getting failed. Can anyone spot where the problems might be.
class Solution
{
public:
//Function to get the maximum total value in the knapsack.
double fractionalKnapsack(int W, Item arr[], int n)
{
// Your code here
pair<double,int> p[n];
for(int i=0;i<n;i++){
p[i].first = arr[i].value/arr[i].weight;
p[i].second = i;
}
sort(p,p+n);
double val =0;
for(int i=n-1;i>=0;i--){
if(arr[p[i].second].weight <= W){
val += arr[p[i].second].value;
W = W - arr[p[i].second].weight;
}
else{
int index = p[i].second;
val += W*((double)arr[index].value/arr[index].weight);
break;
}
}
return val;
}
};