编辑代码


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


public class Greedy_template {


static class Item {
    public String name;
    public double total_weight;
    public double total_value;

    Item(String itemName, double weight, double value) {
        this.name = itemName;
        this.total_weight = weight;
        this.total_value = value;
    }

     Item(Item item) {
        this.name = item.name;
        this.total_weight = item.total_weight;
        this.total_value = item.total_value;
    }
}



    public static LinkedList<Item> pack_fruit(int pack_capacity, Item[] items){
         LinkedList<Item> fruits = new LinkedList<Item>(); // 记录需要装包的水果

         //1. 按照单价从高到低进行排序         
             Arrays.sort(items,new Comparator<Item>() {   
                 @Override
                 public int compare(Item left, Item right) {
                     double left_uni_price =left.total_value/left.total_weight;
                     double right_uni_price= right.total_value/right.total_weight;
                     if(left_uni_price>right_uni_price){
                         return -1;
                     }else if(left_uni_price==right_uni_price){
                         return 0;
                     }else{
                         return 1;
                     }
                 }
         });
         
         int left_pack_capacity=pack_capacity;

         //2. 单价从高到低依次取出水果
        for (int i = 0; i < items.length; ++i) {
            if(left_pack_capacity>=items[i].total_weight){
                left_pack_capacity-=items[i].total_weight;
                fruits.add(new Item(items[i]));
              
            }else{
                double uni_price = items[i].total_value/items[i].total_weight;
                double pack_weight =left_pack_capacity;
                double pack_value= pack_weight *uni_price;
                fruits.add(new Item(items[i].name,pack_weight,pack_value));
                left_pack_capacity = 0;
                break;
            }
        }

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

        LinkedList<Item> fruits = pack_fruit(20, items);

        double max_value = 0;

        System.out.println("装了如下物品:");
        for (int i = 0; i < fruits.size(); ++i) {
            max_value += fruits.get(i).total_value;
            System.out.println(fruits.get(i).name + " " + fruits.get(i).total_weight);
        }

        System.out.println("总价值:" + max_value);

	}

}