[LeetCode] Put Boxes Into the Warehouse II

1580. Put Boxes Into the Warehouse II

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class Solution {
public:
int maxBoxesInWarehouse(vector<int>& boxes, vector<int>& w) {
int l = 0, r = w.size() - 1;
while(l + 1 < r) {
if(w[l] > w[r]) {
if(w[l] < w[l + 1])
w[l + 1] = w[l];
l++;
} else {
if(w[r] < w[r - 1])
w[r - 1] = w[r];
r--;
}
}
sort(boxes.begin(), boxes.end());
int res = 0;
while(res < boxes.size() and (0 <= l or r < w.size())) {
if(0 <= l and r < w.size()) {
if(w[l] >= boxes[res] and w[r] >= boxes[res]) {
if(w[l] < w[r])
l--;
else r++;
res++;
} else if(w[l] >= boxes[res]) {
r++;
} else {
l--;
}
} else if(0 <= l) {
if(w[l] >= boxes[res])
res++;
l--;
} else {
if(w[r] >= boxes[res])
res++;
r++;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/21/PS/LeetCode/put-boxes-into-the-warehouse-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.