编辑代码

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;// 初始化总价值为0
        for (Fruit fruit : fruits1) {// 遍历最大价值水果列表
            System.out.println("物品:" + fruit.name + " 装入" + fruit.weight + " 价值:" + fruit.value); // 输出物品名称、装入重量和价值
            ans += fruit.value; // 累加总价值
        }
        System.out.println("总价值:" + ans);// 输出总价值
    }
}