LeetCode solutions

1829. Maximum Units on a Truck

My accepted Python solution to LeetCode problem 1829, Maximum Units on a Truck, running in 5ms.

  • Difficulty: Easy
  • Python
  • Runtime 5ms
  • Memory 17.4MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 5ms, memory 17.4MB, accepted 2025-12-29.

python
class Solution:
    def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:
        # Greedy: sort by units per box descending, pick most valuable first
        # Time: O(n log n), Space: O(1) - sorting in place
        boxTypes.sort(key=lambda x: -x[1])
        total_units = 0
        for boxes, units in boxTypes:
            take = min(boxes, truckSize)
            total_units += take * units
            truckSize -= take
            if truckSize == 0:
                break
        return total_units

Source