编辑代码

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

class Main {

    static class FruitCom implements Comparator<Fruit> {

        @Override
        public int compare(Fruit o1, Fruit o2) {
            return o2.price - o1.price;
        }
    }

    static class Fruit {
        public int weight;
        public int value;
        public String name;
        public int price;

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

        @Override
        public String toString() {
            return "拿了" + this.name + this.weight + "kg,总价值" + this.value;
        }
    }

    public static List<Fruit> greedy(Fruit[] fruits, int pack) {
        List<Fruit> list = new ArrayList<>();
        Arrays.sort(fruits, new FruitCom());

        for (Fruit fruit : fruits) {
            if (pack >= fruit.weight) {
                list.add(fruit);
                pack -= fruit.weight;
            } else if (pack > 0) {
                fruit.weight = pack;
                fruit.value = fruit.price * pack;
                list.add(fruit);
                pack -= fruit.weight;
            }
        }

        return list;
    }

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

        for (Fruit f : list) {
            System.out.println(f);
        }
    }
}