编辑代码

import java.util.Arrays;

public class BeanBagProblem {
    public static int maxBeanWeight(int[] weights, int W) {
        Arrays.sort(weights);
        int totalWeight = 0;
        for (int i = weights.length - 1; i >= 0; i--) {
            if (totalWeight + weights[i] <= W) {
                totalWeight += weights[i];
            }
        }
        return totalWeight;
    }

    public static void main(String[] args) {
        int[] weights = {3, 5, 2, 7, 10, 4};
        int W = 12;
        System.out.println("最大豆子总重量为:" + maxBeanWeight(weights, W));
    }
}