import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
class Main {
static class Fruit {
String name;
Integer weight;
Double value;
public Fruit(String name, Integer weight, Double value) {
this.name = name;
this.weight = weight;
this.value = value;
}
@Override
public String toString() {
return "Fruit{" +
"name='" + name + '\'' +
", weight=" + weight +
", value=" + value +
'}';
}
}
static class MaxFruitValue {
private List<Fruit> fruits;
private int weight;
public MaxFruitValue(List<Fruit> fruits, int size) {
this.fruits = fruits;
this.weight = size;
}
public List<Fruit> getMaxValue() {
if (Objects.isNull(fruits) || fruits.isEmpty()) {
return new ArrayList<>();
}
fruits = fruits.stream().sorted((f1, f2) -> {
return Double.compare((double) f2.value / f2.weight, (double) (f1.value / f1.weight));
}).collect(Collectors.toList());
List<Fruit> res = new ArrayList<>();
for (int i = 1; i < fruits.size() + 1; i++) {
Fruit fruit = fruits.get(i - 1);
if (weight >= fruit.weight) {
res.add(fruit);
weight -= fruit.weight;
} else {
double unitPrice = (double) fruit.value / fruit.weight;
fruit.value = unitPrice * weight;
fruit.weight = weight;
res.add(fruit);
break;
}
}
return res;
}
}
public static void main(String[] args) {
Fruit fruit1 = new Fruit("苹果", 15, 300.0);
Fruit fruit2 = new Fruit("香蕉", 18, 180.0);
Fruit fruit3 = new Fruit("橘子", 10, 150.0);
Fruit fruit4 = new Fruit("猕猴桃", 9, 270.0);
List<Fruit> fruits = new ArrayList<>();
fruits.add(fruit1);
fruits.add(fruit2);
fruits.add(fruit3);
fruits.add(fruit4);
int fruitNum = 4;
int weight = 20;
MaxFruitValue maxFruitValue = new MaxFruitValue(fruits, weight);
List<Fruit> fruits1 = maxFruitValue.getMaxValue();
double ans = 0;
for (Fruit fruit : fruits1) {
System.out.println("物品:" + fruit.name + " 装入" + fruit.weight + " 价值:" + fruit.value);
ans += fruit.value;
}
System.out.println("总价值:" + ans);
}
}