Sponsored
This approach involves sorting the box types by the number of units per box in descending order. Once sorted, the boxes are loaded onto the truck with the highest units per box first, maximizing the number of units on the truck until it reaches its capacity.
Time Complexity: O(n log n) due to sorting.
Space Complexity: O(1) extra space, as we sort in place.
1import java.util.Arrays;
2
3class Solution {
4 public int maximumUnits(int[][] boxTypes, int truckSize) {
5 Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]);
6
7 int totalUnits = 0;
8 for (int[] box : boxTypes) {
9 int boxesToTake = Math.min(box[0], truckSize);
10 totalUnits += boxesToTake * box[1];
11 truckSize -= boxesToTake;
12 if (truckSize == 0) break;
13 }
14 return totalUnits;
15 }
16}
The Java solution uses Arrays.sort
to sort the box types by units in descending order. It then calculates the maximum units that can be taken given the truck's size constraint.
Instead of sorting by each unit's count, employ counting sort principles to store the total units in an array where the index represents the units per box. This could potentially be faster for large inputs with many boxes and limited unit types.
Time Complexity: O(n + M) where M = 1000 is a constant.
Space Complexity: O(M) for the counting array.
1
Java solution implements a counting array to manage the highest units available. The truck is incrementally packed according to unit priority.