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.
1
Python solution utilizes a counting array approach where units are prioritized by their count indices, providing quick access to maximum unit decisions.