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 - Problem OverviewInput: Box Types and Truck CapacityType 1[1, 3]Type 2[2, 2]Type 3[3, 1]TruckCapacity: 4Strategy: Greedy Selection by Value3 units/boxPriority #12 units/boxPriority #21 unit/boxPriority #3Result: 1×3 + 2×2 + 1×1 = 8 units
Understanding the Visualization
1
Input
Box types with [count, units] and truck capacity
2
Greedy Strategy
Sort by units per box and select highest value first
3
Output
Maximum total units that can fit
Key Takeaway
🎯 Key Insight: Sort by units per box and greedily select highest value boxes first
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