Maximum Units on a Truck — LeetCode 1710 Python Solution
- Problem
- #1710
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are assigned to put some amount of boxes onto one truck. You are given a 2D array boxTypes, where boxTypes[i] = [numberOfBoxesi, numberOfUnitsPerBoxi]: numberOfBoxesi is the number of boxes of type i.
Example
- Input
- boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
- Output
- 8
- Explanation
- There are:
Python solution
class Solution:
def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
ans = 0
for a, b in sorted(boxTypes, key=lambda x: -x[1]):
ans += b * min(truckSize, a)
truckSize -= a
if truckSize <= 0:
break
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n), where n is the length of the two-dimensional array `boxTypes` |
| Space | O(1) to O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1710. Maximum Units on a Truck is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1710. Maximum Units on a Truck?
- LeetCode 1710. Maximum Units on a Truck is rated Easy on LeetCode.
- What topics does LeetCode 1710. Maximum Units on a Truck cover?
- LeetCode 1710. Maximum Units on a Truck is tagged Greedy, Array and Sorting on LeetCode.