Maximum Units on a Truck - 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.
  • numberOfUnitsPerBoxi is the number of units in each box of the type i.

You are also given an integer truckSize, which is the maximum number of boxes that can be put on the truck. You can choose any boxes to put on the truck as long as the number of boxes does not exceed truckSize.

Return the maximum total number of units that can be put on the truck.

Input & Output

Example 1 — Basic Case
$ Input: boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
Output: 8
💡 Note: Take 1 box of type 1 (3 units), 2 boxes of type 2 (4 units), and 1 box of type 3 (1 unit). Total = 3 + 4 + 1 = 8 units.
Example 2 — Limited Capacity
$ Input: boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
Output: 91
💡 Note: Sort by units per box: [5,10], [3,9], [4,7], [2,5]. Take 5 boxes (50 units) + 3 boxes (27 units) + 2 boxes (14 units) = 91 units.
Example 3 — Single Type
$ Input: boxTypes = [[1,1]], truckSize = 1
Output: 1
💡 Note: Only one box type available, take 1 box with 1 unit.

Constraints

  • 1 ≤ boxTypes.length ≤ 1000
  • 1 ≤ numberOfBoxesi, numberOfUnitsPerBoxi ≤ 1000
  • 1 ≤ truckSize ≤ 106

Visualization

Tap to expand
Maximum Units on a Truck INPUT boxTypes Array: Type 0 [1, 3] 1 box, 3 units each Type 1 [2, 2] 2 boxes, 2 units each Type 2 [3, 1] 3 boxes, 1 unit each Truck Size: 4 boxes max truckSize = 4 ALGORITHM STEPS 1 Sort by Units Sort descending by units per box [1,3] [2,2] [3,1] 2 Take Type 0 Take 1 box (3 units) Remaining: 3 slots 3 Take Type 1 Take 2 boxes (4 units) Remaining: 1 slot 4 Take Type 2 Take 1 box (1 unit) Truck full! Total: 3 + 4 + 1 = 8 units 4 boxes used FINAL RESULT 3 2 2 1 Boxes Selected: - 1x Type 0: 1 x 3 = 3 units - 2x Type 1: 2 x 2 = 4 units - 1x Type 2: 1 x 1 = 1 unit Total boxes: 4 (capacity met) Output: 8 [OK] Maximum units achieved Key Insight: Greedy approach works because we want to maximize units, not boxes. By sorting boxes by units per box in descending order and filling the truck greedily, we ensure we always pick the most valuable boxes first. Time: O(n log n) for sorting, Space: O(1). TutorialsPoint - Maximum Units on a Truck | Greedy Approach
Asked in
Amazon 25 Apple 15 Microsoft 10
25.0K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen