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.
1function maximumUnits(boxTypes, truckSize) {
2 boxTypes.sort((a, b) => b[1] - a[1]);
3 let totalUnits = 0;
4 for (const [numberOfBoxes, unitsPerBox] of boxTypes) {
5 const boxesToTake = Math.min(numberOfBoxes, truckSize);
6 totalUnits += boxesToTake * unitsPerBox;
7 truckSize -= boxesToTake;
8 if (truckSize === 0) break;
9 }
10 return totalUnits;
11}
This JavaScript solution sorts the boxTypes
in descending order by units. It increments the total units count by selecting boxes from highest units per box type.
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.
1using namespace std;
#define MAX_UNITS 1000
class Solution {
public:
int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
vector<int> count(MAX_UNITS + 1, 0);
for (const auto& box : boxTypes) {
count[box[1]] += box[0];
}
int totalUnits = 0;
for (int i = MAX_UNITS; i > 0 && truckSize > 0; --i) {
if (count[i] > 0) {
int boxesToTake = min(truckSize, count[i]);
totalUnits += boxesToTake * i;
truckSize -= boxesToTake;
}
}
return totalUnits;
}
};
The C++ solution employs a counting approach focusing on unit counts, and incrementally takes maximum units based on the counting index.