Maximum Units on a Truck
Difficulty: Easy · Pattern: Greedy · LeetCode #1710
boxTypes[i] = [numberOfBoxes, unitsPerBox]. The truck holds at most truckSize boxes. Return the maximum total number of units you can load.
Examples
text
boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 → 8 (3 + 2·2 + 1·1)
boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 → 91Hints
- Every box takes one slot, whatever its type. Which boxes deserve the slots?
Approach
Sort the types by unitsPerBox descending, then take min(count, remaining) boxes of each type until the truck is full.
The greedy is optimal because all boxes "weigh" the same (one slot each). It's a fractional knapsack with unit weights. Counting sort works too, since units ≤ 1000.
Complexity
Time: O(n log n). Space: O(n).
Python solution
def maximumUnits(boxTypes, truckSize):
total = 0
for cnt, units in sorted(boxTypes, key=lambda b: -b[1]):
take = min(cnt, truckSize)
total += take * units
truckSize -= take
if truckSize == 0:
break
return totalJavaScript solution
function maximumUnits(boxTypes, truckSize) {
let total = 0;
for (const [cnt, units] of [...boxTypes].sort((a, b) => b[1] - a[1])) {
const take = Math.min(cnt, truckSize);
total += take * units; truckSize -= take;
if (!truckSize) break;
}
return total;
}