-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractional Knapsack.java
More file actions
41 lines (37 loc) · 1.01 KB
/
Copy pathFractional Knapsack.java
File metadata and controls
41 lines (37 loc) · 1.01 KB
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
39
40
41
import java.util.Arrays;
import java.util.Comparator;
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)
{
Arrays.sort(arr, new Comparator<Item>() {
@Override
public int compare(Item a, Item b) {
double r1 = (double) a.value / a.weight;
double r2 = (double) b.value / b.weight;
if (r1 < r2) return 1;
else if (r1 > r2) return -1;
else return 0;
}
});
double res = 0.0;
for (int i = 0; i < n; i++) {
if (arr[i].weight <= W) {
res += arr[i].value;
W -= arr[i].weight;
} else {
res += arr[i].value * ((double) W / arr[i].weight);
break;
}
}
return res;
}
}