-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFractionalKnapsack.java
More file actions
44 lines (44 loc) · 1.48 KB
/
FractionalKnapsack.java
File metadata and controls
44 lines (44 loc) · 1.48 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
42
43
44
import java.util.*;
class Item {
int weight;
int value;
public Item(int weight, int value) {
this.weight = weight;
this.value = value;
}
}
public class FractionalKnapsack {
static double getMaxValue(Item[] items, int capacity) {
// Sort items by value/weight ratio in descending order
Arrays.sort(items, (Item item1, Item item2) -> {
double ratio1 = item1.value / item1.weight;
double ratio2 = item2.value / item2.weight;
return Double.compare(ratio2, ratio1);
});
double totalValue = 0;
int currentWeight = 0;
for (Item item : items) {
if (currentWeight + item.weight <= capacity) {
// If we can take the whole item, take it
currentWeight += item.weight;
totalValue += item.value;
} else {
// If we can't take the whole item, take a fraction of it
int remainingCapacity = capacity - currentWeight;
totalValue += ( item.value / item.weight) * remainingCapacity;
break;
}
}
return totalValue;
}
public static void main(String[] args) {
Item[] items = {
new Item(10, 60),
new Item(20, 100),
new Item(30, 120)
};
int capacity = 50;
double maxValue = getMaxValue(items, capacity);
System.out.printf("Maximum value in Knapsack = %.2f", maxValue);
}
}