编辑代码

//package greedy;

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

public class GreedyTemplate {
    public static LinkedList<Item> packBean(int packCapacity, Item[] items){
         LinkedList<Item> beans = new LinkedList<Item>(); // 记录需要装包的豆子

         //1. 按照单价从高到低进行排序
         Arrays.sort(items, new Comparator<Item>(){
             public int compare(Item left, Item right){
                 double leftUnitPrice = left.totalValue/left.totalWeight;
                 double rightUnitPrice = right.totalValue/right.totalWeight;
                 if(leftUnitPrice > rightUnitPrice){
                     return -1;
                 }else if(leftUnitPrice == rightUnitPrice){
                     return 0;
                 }else{
                     return 1;
                 }
             }

         });

         //2. 单价从高到低依次取出豆子
         int leftPackCapacity = packCapacity;
         for(int i = 0; i < items.length; ++i){
             if(leftPackCapacity>items[i].totalWeight){
                 leftPackCapacity -= items[i].totalWeight;
                 beans.add(new Item(items[i]));
             }else{
                 double unitPrice = items[i].totalValue/items[i].totalWeight;
                 double packWeight = leftPackCapacity;
                 double packValue = packWeight * unitPrice;
                 beans.add(new Item(items[i].name, packWeight, packValue));
                 leftPackCapacity = 0;
                 break;
             }
         }

         return beans;
    }
    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> beans = packBean(20, items);

        double maxValue = 0;

        System.out.println("装了如下物品:");
        for (int i = 0; i < beans.size(); ++i) {
            maxValue += beans.get(i).totalValue;
            System.out.println(beans.get(i).name + " " + beans.get(i).totalWeight);
        }

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

	}

}

class Item {
    public String name;
    public double totalWeight;
    public double totalValue;

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

     Item(Item item) {
        this.name = item.name;
        this.totalWeight = item.totalWeight;
        this.totalValue = item.totalValue;
    }
}