Python 1710.py
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
# sort by units per box
boxTypes.sort(key = lambda x : -x[1])
result = 0
for boxes, units in boxTypes:
take = min(boxes, truckSize)
truckSize -= take
result += take * units
if truckSize == 0:
break
return result
Difficulty
and has an acceptance rate of about 74% (400k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the classic “maximum units on a truck” problem by selecting boxes from a list of box types in a way that maximizes the total number of units that can be loaded onto a truck with a limited capacity. The algorithm follows a greedy strategy: it always picks boxes from the type that offers the highest units per box first, then proceeds to the next best type until the truck is full or no more boxes are available. The code is concise, leverages Python’s built-in sorting, and includes an early-exit condition that prevents unnecessary iteration once the truck capacity has been satisfied.
Sorting by Units per Box
The first logical step is to order the input boxTypes so that the type with the greatest units per box appears first. This is achieved with an in-place sort that uses a lambda function to extract the second element of each sub-list (the units per box) and negates it to obtain descending order.
boxTypes.sort(key = lambda x : -x[1])
By sorting in place, the algorithm avoids the overhead of creating a new list, and the use of a key function ensures that the comparison is performed only on the relevant attribute, which is more efficient than sorting on the entire sub-list.
Greedy Accumulation of Units
After sorting, the algorithm iterates over the ordered boxTypes. For each type, it determines how many boxes can be taken without exceeding the remaining truck capacity. The min function captures the smaller of the available boxes of that type and the current truckSize. The chosen quantity is then subtracted from truckSize, and the corresponding units are added to the running total result.
for boxes, units in boxTypes:
take = min(boxes, truckSize)
truckSize -= take
result += take * units
The use of tuple unpacking (boxes, units) makes the code readable and eliminates the need for index-based access. Multiplying take by units directly computes the contribution of the current box type to the total units, avoiding any intermediate loops.
Early Termination When the Truck Is Full
A crucial optimization is the check for a zero truckSize after each iteration. If the truck has reached its capacity, the loop breaks immediately, preventing further unnecessary processing of remaining box types.
if truckSize == 0:
break
This early exit is particularly beneficial when the truck can be filled after processing only a few of the highest-value box types, which is common in scenarios where the truck size is relatively small compared to the total number of boxes.
Edge Cases Handled by the Implementation
The code gracefully handles several boundary conditions without additional conditional logic. When boxTypes is empty, the initial sort is a no-op and the subsequent loop does not execute, resulting in a return value of zero. If truckSize is zero from the start, the loop body never runs because the min function will always yield zero, and the early-termination check will trigger immediately, again returning zero. When a particular box type contains more boxes than the remaining truck capacity, the min function caps the number taken to exactly fill the truck, ensuring that the algorithm never exceeds the allowed capacity. Conversely, if the total number of boxes across all types is less than truckSize, the loop will exhaust all box types, leaving a positive truckSize that is simply ignored, and the final result reflects the sum of all available units.
Performance Considerations
The algorithm’s performance is driven by two main factors: the sorting step and the linear scan of the sorted list. Sorting is performed once and benefits from Python’s highly optimized Timsort algorithm, which adapts to existing order in the data and runs efficiently on real-world inputs. The subsequent iteration processes each box type at most once, and the use of simple arithmetic operations (min, subtraction, multiplication) ensures minimal overhead per element. The early-termination condition further reduces work in cases where the truck fills early, avoiding the need to traverse the entire list. By modifying the input list in place and avoiding auxiliary data structures, the implementation also minimizes memory pressure, which can be advantageous when dealing with large collections of box types.
ELI5 - Simplified Explanation
Imagine an imaginary truck that has a limited amount of space for boxes. These boxes have different numbers of treats hidden inside them, and some boxes have many more treats than others. The goal is to fill the truck so that it carries the biggest mountain of treats possible.
First, the code looks at all the boxes and figures out which ones have the most treats inside. Think of it like organizing a pile of boxes so that the ones with the most treasures are always sitting right on top.
Next, the code starts putting boxes into the truck one by one. It picks the best box from the top of the pile first because that box holds the most treats. It checks to see if there is enough space left in the truck to fit that box. If the truck still has room, it puts the box inside and adds those treats to the total pile.
The truck keeps doing this over and over again, always picking the best remaining box. If the truck runs out of space and becomes completely full, it stops picking up new boxes. It is like a fun game of trying to pack a suitcase with the most valuable toys before heading off on a trip.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | ||||||
| WalkCCC | C++ | Python | Java | ||||||||
| leetcode.ca | C++ | Python | Java | Go | Rust | TS | |||||
| Progiez | C++ | Python | Java | ||||||||
| github | black-shadows | C++ | |||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JS | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| YuriSpiridonov | Python | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| halfrost | Go | ||||||||||
| haoel | C++ | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| lkwq007 | Python | ||||||||||
| MacJim | C++ | ||||||||||
| muhammadfarhankt | Go | ||||||||||
| suxrobGM | C# | ||||||||||
| trung-hn | Python | ||||||||||
| varunu28 | Java | ||||||||||
| vthwang | Java | ||||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 2279: Maximum Bags With Full Capacity of Rocks
Solved On The Same Day
- problem 1217: Minimum Cost to Move Chips to The Same Position
- problem 1221: Split a String in Balanced Strings
- problem 1323: Maximum 69 Number
- problem 969: Pancake Sorting
- problem 991: Broken Calculator
- problem 1605: Find Valid Matrix Given Row and Column Sums
- problem 630: Course Schedule III
- problem 1425: Constrained Subsequence Sum
- problem 2147: Number of Ways to Divide a Long Corridor
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality