Skip to content

Commit

Permalink
Create Fractional_knapsack
Browse files Browse the repository at this point in the history
  • Loading branch information
Saurabh0625 authored Oct 28, 2022
1 parent 079e0ae commit a51b3be
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions Fractional_knapsack
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include <bits/stdc++.h>

using namespace std;

struct Item {
int value;
int weight;
};
class Solution {
public:
bool static comp(Item a, Item b) {
double r1 = (double) a.value / (double) a.weight;
double r2 = (double) b.value / (double) b.weight;
return r1 > r2;
}
// function to return fractionalweights
double fractionalKnapsack(int W, Item arr[], int n) {

sort(arr, arr + n, comp);

int curWeight = 0;
double finalvalue = 0.0;

for (int i = 0; i < n; i++) {

if (curWeight + arr[i].weight <= W) {
curWeight += arr[i].weight;
finalvalue += arr[i].value;
} else {
int remain = W - curWeight;
finalvalue += (arr[i].value / (double) arr[i].weight) * (double) remain;
break;
}
}

return finalvalue;

}
};
int main() {
int n = 3, weight = 50;
Item arr[n] = { {100,20},{60,10},{120,30} };
Solution obj;
double ans = obj.fractionalKnapsack(weight, arr, n);
cout << "The maximum value is " << setprecision(2) << fixed << ans;
return 0;
}

0 comments on commit a51b3be

Please sign in to comment.