forked from durgesh2001/hacktoberfest_demo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractional Knapsack.cpp
More file actions
38 lines (35 loc) · 870 Bytes
/
Fractional Knapsack.cpp
File metadata and controls
38 lines (35 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/*
struct Item{
int value;
int weight;
};
*/
bool comp(Item a,Item b){
double r1=(double)a.value/(double)a.weight;
double r2=(double)b.value/(double)b.weight;
return r1>r2;
}
class Solution
{
public:
//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 currWeight=0;
double finalValue=0.0;
for(int i=0;i<n;i++){
if(currWeight+arr[i].weight<=W){
currWeight+=arr[i].weight;
finalValue+=arr[i].value;
}
else{
int remain=W-currWeight;
finalValue+=(arr[i].value/(double)arr[i].weight)*(double)remain;
break;
}
}
return finalValue;
}
};