Put Boxes Into the Warehouse II - Problem
Imagine you're managing a warehouse logistics operation! You have a collection of boxes with different heights and a warehouse with rooms of varying ceiling heights. Your goal is to maximize the number of boxes you can store.
You're given two arrays:
boxes- heights of boxes you need to storewarehouse- ceiling heights of warehouse rooms (indexed 0 to n-1 from left to right)
Storage Rules:
- ๐ฆ Boxes cannot be stacked on top of each other
- ๐ You can rearrange boxes in any order before storing
- โ๏ธ Boxes can be inserted from either the left OR right side of the warehouse
- ๐ซ If a box is too tall for a room, it gets blocked and cannot reach rooms beyond that point
Return the maximum number of boxes you can successfully store in the warehouse.
Input & Output
example_1.py โ Standard Case
$
Input:
boxes = [4, 3, 4, 1], warehouse = [5, 3, 3, 4, 1]
โบ
Output:
3
๐ก Note:
We can place boxes with heights [1, 3, 4]. The box with height 1 can go in room 4 (accessed from right), box with height 3 can go in rooms 1 or 2 (accessed from left), and box with height 4 can go in room 3 (accessed from right).
example_2.py โ All Boxes Fit
$
Input:
boxes = [1, 2, 2, 3], warehouse = [3, 4, 1, 2]
โบ
Output:
3
๐ก Note:
Room 2 has height 1, so boxes coming from left get blocked after room 1. From right, boxes get blocked after room 3. We can place boxes [1, 2, 2] optimally.
example_3.py โ Edge Case
$
Input:
boxes = [1, 2, 3], warehouse = [1, 1, 1]
โบ
Output:
1
๐ก Note:
All warehouse rooms have height 1, so we can only place the box with height 1. The boxes with heights 2 and 3 are too tall.
Constraints
- 1 โค boxes.length โค 105
- 1 โค warehouse.length โค 105
- 1 โค boxes[i], warehouse[i] โค 109
- Boxes can be inserted from either left or right side
- Boxes cannot be stacked
Visualization
Tap to expand
Understanding the Visualization
1
Analyze Access Routes
Calculate how tall boxes can be when approaching from left vs right side
2
Sort by Priority
Sort boxes by height - smallest boxes should get priority for tight spaces
3
Optimal Assignment
Use two pointers to assign each box to the most restrictive available position
Key Takeaway
๐ฏ Key Insight: Sort boxes by height and use two pointers to greedily assign the smallest available box to the most restrictive position, maximizing total storage capacity.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code