Maximum Units on a Truck — LeetCode 1710 Python Solution

EasyGreedyArraySorting
Problem
#1710
Pattern
Greedy
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n \times \log n), where n is the length of the two-dimensional array `boxTypes`
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview