编辑代码

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

class Bean {
    int price;
    int weight;

    public Bean(int price, int weight) {
        this.price = price;
        this.weight = weight;
    }
}

public class BeanKnapsack {
    public static double getMaxValue(Bean[] beans, int capacity) {
        // 计算单位重量价格
        for (Bean bean : beans) {
            bean.price = bean.price / bean.weight;
        }

        // 按单位重量价格从高到低排序
        Arrays.sort(beans, Comparator.comparingInt(b -> -b.price));

        // 贪心算法
        double maxValue = 0;
        for (Bean bean : beans) {
            if (capacity >= bean.weight) {
                maxValue += bean.price * bean.weight;
                capacity -= bean.weight;
            } else {
                maxValue += bean.price * capacity;
                break;
            }
        }

        return maxValue;
    }

    public static void main(String[] args) {
        Bean[] beans = {new Bean(60, 10), new Bean(100, 20), new Bean(120, 30)};
        int capacity = 50;
        System.out.println("Max Value: " + getMaxValue(beans, capacity)); // 输出:Max Value: 240.0
    }
}