一刷 06/2022
Version #1 Sort the array
Time O(NlogN)
Space O(N) ~ O(logN) depending on the sorting algorithm
Runtime: 13 ms, faster than 50.13% of Java online submissions for Maximum Units on a Truck.
Memory Usage: 51.2 MB, less than 33.19% of Java online submissions for Maximum Units on a Truck.
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
Arrays.sort(boxTypes, (a, b) -> Integer.compare(b[1], a[1]));
int total = 0;
int i = 0;
while (truckSize > 0 && i < boxTypes.length) {
int box = boxTypes[i][0] <= truckSize ? boxTypes[i][0] : truckSize;
total += box * boxTypes[i][1];
truckSize -= box;
i++;
}
return total;
}
}
No comments:
Post a Comment