Put Boxes Into the Warehouse II - Problem

You are given two arrays of positive integers, boxes and warehouse, representing the heights of some boxes of unit width and the heights of n rooms in a warehouse respectively.

The warehouse's rooms are labeled from 0 to n - 1 from left to right where warehouse[i] (0-indexed) is the height of the ith room.

Boxes are put into the warehouse by the following rules:

  • Boxes cannot be stacked.
  • You can rearrange the insertion order of the boxes.
  • Boxes can be pushed into the warehouse from either side (left or right)
  • If the height of some room in the warehouse is less than the height of a box, then that box and all other boxes behind it will be stopped before that room.

Return the maximum number of boxes you can put into the warehouse.

Input & Output

Example 1 — Basic Case
$ Input: boxes = [4,3,4,1], warehouse = [5,3,3,4,1]
Output: 3
💡 Note: We can place 3 boxes: box with height 1 can go anywhere, boxes with height 3 can fit in positions with height ≥3, and one box with height 4 can fit in position with height ≥4. From left: effective heights are [5,3,3,3,1]. From right: effective heights are [1,1,1,1,1]. Optimal placement yields 3 boxes.
Example 2 — Single Room
$ Input: boxes = [1,2,2,3,4], warehouse = [3]
Output: 1
💡 Note: Only one room available with height 3. We can place at most 1 box (any box with height ≤3). The optimal choice is to place one of the boxes with height 1, 2, or 3.
Example 3 — No Fit
$ Input: boxes = [5,5,5], warehouse = [2,1,1]
Output: 0
💡 Note: All boxes have height 5, but all warehouse rooms have height less than 5. No boxes can be placed.

Constraints

  • 1 ≤ boxes.length ≤ 105
  • 1 ≤ warehouse.length ≤ 105
  • 1 ≤ boxes[i], warehouse[i] ≤ 109

Visualization

Tap to expand
Put Boxes Into Warehouse II: Bi-directional Placement4341Boxes to Place53341Warehouse RoomsBox 1 (height 1) → rightmost roomBox 3 (height 3) → left room with height 3Box 4 (height 4) → room with height 4Box 4 (height 4) cannot fit in remaining roomsMaximum boxes placed: 3
Understanding the Visualization
1
Input
Boxes [4,3,4,1] and Warehouse [5,3,3,4,1]
2
Process
Calculate effective heights and match with sorted boxes
3
Output
Maximum 3 boxes can be placed
Key Takeaway
🎯 Key Insight: Calculate effective heights from both directions and use greedy placement with sorted boxes for optimal results
Asked in
Amazon 25 Google 18 Microsoft 12
23.5K Views
Medium Frequency
~25 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