pick larger unit first, so sort by numberOfUnitsPerBoxi desc
ticky part is use left box number to gen the result (not like 背包問題, 只有一個包, 這裡有多個紙箱可以用, 所以可以用 貪心)
time: O(nlogn)
space: O(1)
classSolution {publicintmaximumUnits(int[][] boxTypes,int truckSize) {Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]); // sort by unit desc, use unit bigger oneint res =0;for (int boxType[] : boxTypes) {int boxNum =Math.min(truckSize, boxType[0]); // use < truckSize's box number res += boxNum * boxType[1]; truckSize -= boxNum;if (truckSize ==0) {return res; } }return res; }}/*[[5,10],[3,9], [4,7], [2,5]]10 , 5 use 55*10 = 50. 10-5 = 55, 3 use 327 3*9, 5-3 = 22 4 use 214 2*7 2, 4 = 2= 91boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]maximum number of boxes: truckSizeYou can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.maximum total number of units 1 + 2 + 1 => weight5*10 503*9 27*/