Maximum Units on a Truck - Problem
Imagine you're a logistics coordinator tasked with optimizing truck loading! You have one truck with limited capacity and multiple types of boxes, each containing different numbers of valuable units.
Given a 2D array boxTypes where boxTypes[i] = [numberOfBoxes, unitsPerBox]:
numberOfBoxes- how many boxes of type i are availableunitsPerBox- value/units contained in each box of type i
You're also given truckSize - the maximum number of boxes the truck can carry.
Goal: Select boxes to maximize the total units loaded onto the truck without exceeding the truck's capacity.
Example: If you have box types [[1,3], [2,2], [3,1]] and truck capacity 4, you should prioritize high-value boxes first: take 1 box with 3 units, then 2 boxes with 2 units each, then 1 box with 1 unit = 10 total units.
Input & Output
example_1.py โ Basic Example
$
Input:
boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
โบ
Output:
8
๐ก Note:
Take 1 box of type with 3 units, 2 boxes of type with 2 units each, and 1 box of type with 1 unit. Total = 1ร3 + 2ร2 + 1ร1 = 8 units using exactly 4 boxes.
example_2.py โ Excess 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 all: 5ร10 + 3ร9 + 2ร7 = 91 units using exactly 10 boxes.
example_3.py โ Limited Capacity
$
Input:
boxTypes = [[1,3],[5,5],[2,4],[4,1]], truckSize = 3
โบ
Output:
13
๐ก Note:
Sort by units per box: [5,5], [2,4], [1,3], [4,1]. Take 3 boxes with 5 units each = 3ร5 = 15 units, but we can only take 3 boxes total, so we get 3ร5 = 15. Wait, let me recalculate: we have [5,5] so we can take all 5 boxes, but truck only holds 3, so 3ร5 = 15. Actually, we take 3 out of the 5 boxes of type [5,5] = 15 units.
Constraints
- 1 โค boxTypes.length โค 1000
- 1 โค numberOfBoxesi, numberOfUnitsPerBoxi โค 1000
- 1 โค truckSize โค 106
- Box types can have duplicate unit values
- You must respect the truck capacity exactly
Visualization
Tap to expand
Understanding the Visualization
1
Assess the Treasure
Line up all chest types and identify their gold-per-chest value
2
Sort by Value
Arrange chests from most valuable to least valuable per chest
3
Load Greedily
Always take the most valuable chests first until ship is full
4
Maximize Gold
This greedy strategy guarantees maximum treasure value
Key Takeaway
๐ฏ Key Insight: Greedy works because there's never a benefit to taking lower-value items when higher-value items are available - always prioritize maximum value per unit of capacity!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code