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; } }