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.
1def maximumUnits(boxTypes, truckSize):
2 boxTypes.sort(key=lambda x: -x[1])
3 total_units = 0
4 for numberOfBoxes, unitsPerBox in boxTypes:
5 boxes_to_take = min(numberOfBoxes, truckSize)
6 total_units += boxes_to_take * unitsPerBox
7 truckSize -= boxes_to_take
8 if truckSize == 0:
9 break
10 return total_units
Python solution leverages sorting using lambda to order box types by units and iteratively fill the truck to maximize units.
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
This approach uses a counting array where the index represents units per box to aggregate total boxes available. The truck is filled according to the highest units available in the count array.