解答
1class Solution { 2 public int maximumUnits(int[][] boxTypes, int truckSize) { 3 Arrays.sort(boxTypes, new Comparator<int[]>() { 4 @Override 5 public int compare(int[] o1, int[] o2) { 6 return o2[1] - o1[1]; 7 } 8 }); 9 int result = 0; 10 for (int i = 0; i < boxTypes.length; ++i) { 11 int[] boxType = boxTypes[i]; 12 int count = boxType[0]; 13 while (truckSize > 0 && count > 0) { 14 --count; 15 --truckSize; 16 result += boxType[1]; 17 } 18 } 19 20 return result; 21 } 22} 23
总结
先对箱子排序,然后从大到小,遍历箱子,并填充上车,直到上车被装满。
《LeetCode第1710题 - 卡车上的最大单元数》 是转载文章,点击查看原文。