力扣上提交的代码
class Solution {public int maximumUnits(int[][] boxTypes, int truckSize) {int res = 0;//存储可以装载单元的最大总数//根据二维数组的第二列数据降序排列Arrays.sort(boxTypes,(o1, o2) -> o2[1]-o1[1]);for (int i = 0; i<boxTypes.length && truckSize>0 ; i++) {//二维数组的length是行数int num = Math.min(boxTypes[i][0],truckSize);//每一次的箱子数取两者中最小的res += num*boxTypes[i][1];truckSize -= boxTypes[i][0];}return res;}
}
用IDEA调试的代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;public class maximumUnits1710 {public static void main(String[] args) {int[][] boxTypes = {{1,3},{2, 2},{3, 1}};int truckSize = 4;//箱子数int res = maximumUnits(boxTypes,truckSize);System.out.println(res);}public static int maximumUnits(int[][] boxTypes, int truckSize) {int res = 0;//存储可以装载单元的最大总数//根据二维数组的第二列数据降序排列Arrays.sort(boxTypes,(o1, o2) -> o2[1]-o1[1]);for (int i = 0; i<boxTypes.length && truckSize>0 ; i++) {//二维数组的length是行数int num = Math.min(boxTypes[i][0],truckSize);//每一行的箱子数取两者中最小的res += num*boxTypes[i][1];truckSize -= boxTypes[i][0];}return res;}
}