Solution 1, Using a PriorityQueue

class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        PriorityQueue<int[]> queue = new PriorityQueue<>((a,b)->b[1]-a[1]);
        for(int[] boxType:boxTypes){
            queue.offer(boxType);
        }
        
        int res = 0;
        while(truckSize>0&&!queue.isEmpty()){
            int[] boxType = queue.poll();
            int box = boxType[0];
            int unitNum = boxType[1];
            int boxNum = Math.min(box, truckSize);
            res+=unitNum*boxNum;
            truckSize-=boxNum;  
        }
        return res;
    }
}

Solution 2, Sort the box array directly

class Solution {
    public int maximumUnits(int[][] boxTypes, int truckSize) {
        Arrays.sort(boxTypes, (a,b)->b[1]-a[1]);
        
        int res = 0, index=0;
        while(truckSize>0&&index<boxTypes.length){
            int[] boxType = boxTypes[index++];
            int box = boxType[0];
            int unitNum = boxType[1];
            int boxNum = Math.min(box, truckSize);
            res+=unitNum*boxNum;
            truckSize-=boxNum;  
        }
        return res;
    }
}

 

posted on 2022-03-22 03:53  阳光明媚的菲越  阅读(18)  评论(0编辑  收藏  举报