-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFractionalKnapsack.java
70 lines (43 loc) · 1.31 KB
/
FractionalKnapsack.java
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.util.Arrays;
public class FractionalKnapsack {
static class Item implements Comparable<Item> {
int weight, value;
public Item(int v, int w) {
value = v;
weight = w;
}
double getRatio() {
return value / (double) weight;
}
@Override
public int compareTo(Item b) {
return Double.compare(b.getRatio(), getRatio());
}
}
static double getMaxValue(Item[] items, int maxWeight) {
Arrays.sort(items);
int currentWeight = 0;
double currentValue = 0.0;
for (Item item : items) {
if (currentWeight + item.weight <= maxWeight) {
currentWeight += item.weight;
currentValue += item.value;
} else {
int remaining = maxWeight - currentWeight;
currentValue += remaining * item.getRatio();
break;
}
}
return currentValue;
}
public static void main(String[] args) {
Item[] items = new Item[]{
new Item(60, 10),
new Item(100, 20),
new Item(20, 50),
new Item(120, 30),
new Item(10, 2)
};
System.out.println(getMaxValue(items, 75));
}
}