编辑代码

import java.util.Arrays;

public class FruitBackpack {

    static class Fruit implements Comparable<Fruit> {
        String name;
        int weight;
        int value;

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

        @Override
        public int compareTo(Fruit other) {
            // 按照单位重量价值降序排列
            return Double.compare((double) other.value / other.weight, (double) this.value / this.weight);
        }
    }

    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 maxWeight = 20;

        Arrays.sort(fruits);

        int currentWeight = 0;
        int totalValue = 0;

        System.out.println("装水果的策略:");
        for (Fruit fruit : fruits) {
            if (currentWeight + fruit.weight <= maxWeight) {
                // 能装下当前水果
                System.out.println("装入 " + fruit.name + ",重量:" + fruit.weight + "kg,价值:" + fruit.value + "元");
                currentWeight += fruit.weight;
                totalValue += fruit.value;
            } else {
                // 装不下当前水果
                double remainingWeight = maxWeight - currentWeight;
                double portion = remainingWeight / fruit.weight;
                System.out.println("装入部分 " + fruit.name + ",重量:" + remainingWeight + "kg,价值:" + portion * fruit.value + "元");
                totalValue += portion * fruit.value;
                break; // 背包已装满,结束循环
            }
        }

        System.out.println("背包中装入水果的总价值:" + totalValue + "元");
    }
}