编辑代码

import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedList;

class Fruit {
    public String name;
    public double weight;
    public double value;

    Fruit(String name, double weight, double value) {
        this.name = name;
        this.weight = weight;
        this.value = value;
    }

    Fruit(Fruit fruit) {
        this.name = fruit.name;
        this.weight = fruit.weight;
        this.value = fruit.value;
    }

    // 求水果的单价
    public double unitPrice() {
        return value / weight;
    }

    public static LinkedList<Fruit> packFruits(int backpackCapacity, Fruit[] fruits) {
        LinkedList<Fruit> selectedFruits = new LinkedList<>(); // 记录选择的水果

        // 1. 按照单价从高到低进行排序
        Arrays.sort(fruits, Comparator.comparingDouble(Fruit::unitPrice).reversed());

        // 2. 单价从高到低依次选取水果
        for (Fruit fruit : fruits) {
            if (backpackCapacity >= fruit.weight) {
                selectedFruits.add(new Fruit(fruit));
                backpackCapacity -= fruit.weight;
            } else {
                double fraction = backpackCapacity / fruit.weight;
                selectedFruits.add(new Fruit(fruit.name, fraction * fruit.weight, fraction * fruit.value));
                break;
            }
        }

        return selectedFruits;
    }

    public static void main(String[] args) {
        Fruit[] fruits = {
                new Fruit("苹果", 15, 300),  
                new Fruit("香蕉", 18, 180),  
                new Fruit("橘子", 10, 150), 
                new Fruit("猕猴桃", 9, 270)  
        };

        int backpackCapacity = 20;

        LinkedList<Fruit> selectedFruits = packFruits(backpackCapacity, fruits);

        double totalValue = 0;

        System.out.println("背包里面应装以下水果:");
        for (int i = 0; i < selectedFruits.size(); ++i) {
            totalValue += selectedFruits.get(i).value;
            System.out.println(selectedFruits.get(i).name + " " + selectedFruits.get(i).weight+"kg");
        }

        System.out.println("总价值:" + totalValue+"元");
    }
}