Maximum Units on a Truck (LeetCode 1710): Solution and Explanation
Each box type has a box count and a number of units per box. Load at most truckSize boxes onto one truck and return the largest total number of units it can carry.
Intuition
The truck limits the number of boxes, not their weight or their units. Every box costs exactly one slot, whatever it holds.
So the question for each slot is simple: which available box holds the most units? Put that one in. Choosing a poorer box for any slot while a richer one is left over can only lose units.
That means sorting the types by units per box, largest first, and taking whole types in that order. Only the last type touched may be taken partially, when the truck runs out of room.
Approach: Sort by units per box, then fill
- Sort
boxTypesbynumberOfUnitsPerBoxin decreasing order. - Set
units = 0. - For each type, take
min(count, truckSize)boxes, addtake * perBoxtounitsand subtracttakefromtruckSize. - Stop as soon as
truckSizereaches 0, then returnunits.
Step-by-step example
boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
- Sorted by units per box: [1,3], [2,2], [3,1] (already in order).
- Type [1,3]: 1 box fits. Load it for 3 units. units = 3, 3 slots left.
- Type [2,2]: both boxes fit. Load them for 4 units. units = 7, 1 slot left.
- Type [3,1]: only 1 of its 3 boxes fits. Load it for 1 unit. units = 8, 0 slots left.
- The truck is full. Return 8.
Code: Python, Java, C++
1class Solution:
2 def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
3 boxTypes.sort(key=lambda b: -b[1])
4 units = 0
5 for count, per_box in boxTypes:
6 if truckSize == 0:
7 break
8 take = min(count, truckSize)
9 units += take * per_box
10 truckSize -= take
11 return units1class Solution {
2 public int maximumUnits(int[][] boxTypes, int truckSize) {
3 Arrays.sort(boxTypes, (a, b) -> b[1] - a[1]);
4 int units = 0;
5 for (int[] box : boxTypes) {
6 if (truckSize == 0) {
7 break;
8 }
9 int take = Math.min(box[0], truckSize);
10 units += take * box[1];
11 truckSize -= take;
12 }
13 return units;
14 }
15}1class Solution {
2public:
3 int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) {
4 sort(boxTypes.begin(), boxTypes.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] > b[1]; });
5 int units = 0;
6 for (auto& box : boxTypes) {
7 if (truckSize == 0) {
8 break;
9 }
10 int take = min(box[0], truckSize);
11 units += take * box[1];
12 truckSize -= take;
13 }
14 return units;
15 }
16};Time and space complexity
O(n log n)
Sorting the n box types dominates. The loading pass is O(n).
O(1)
Only a few counters besides the in-place sort (which may use O(log n) stack depending on the language).
Other approaches
Counting sort on units per box (time O(n + U) with U = 1000, space O(U))
Units per box is at most 1000, so add each type's count to a bucket indexed by units, then walk the buckets from 1000 down to 1, taking boxes until the truck is full.
Max-heap (time O(n log n), space O(n))
Push every type into a max-heap keyed by units per box and pop the richest type until the truck is full. Same idea, useful when types arrive as a stream.
Common mistakes
- Sorting by the number of boxes, or by the total units of a type (count x perBox). The truck limit is in boxes, so only units per box matters.
- Taking a whole type even when it does not fit. Take min(count, remaining) boxes.
- Forgetting the case where all boxes fit with room to spare. The loop simply ends and every box is loaded.
- Treating it as 0/1 knapsack. Boxes are all the same size, so the greedy order is exact and no DP is needed.
Frequently asked questions
Why is greedy correct here when knapsack usually needs DP?
Knapsack needs DP because items have different sizes. Here every box takes one slot, so swapping any loaded box for a richer unused one never breaks the limit and never lowers the total.
Does the order of ties matter?
No. Two types with the same units per box contribute the same units per slot, so it does not matter which one fills the slots first.
Can the answer overflow a 32-bit integer?
No. At most 1000 types with 1000 boxes of 1000 units each gives 10^9, which fits in a signed 32-bit integer.