Maximum Units on a Truck (LeetCode 1710): Solution and Explanation

Easy
Array
Greedy
Sorting

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

  1. Sort boxTypes by numberOfUnitsPerBox in decreasing order.
  2. Set units = 0.
  3. For each type, take min(count, truckSize) boxes, add take * perBox to units and subtract take from truckSize.
  4. Stop as soon as truckSize reaches 0, then return units.

Step-by-step example

boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
  1. Sorted by units per box: [1,3], [2,2], [3,1] (already in order).
  2. Type [1,3]: 1 box fits. Load it for 3 units. units = 3, 3 slots left.
  3. Type [2,2]: both boxes fit. Load them for 4 units. units = 7, 1 slot left.
  4. Type [3,1]: only 1 of its 3 boxes fits. Load it for 1 unit. units = 8, 0 slots left.
  5. 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 units
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n log n)

Sorting the n box types dominates. The loading pass is O(n).

Space

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.