Skip to content

1580. Put Boxes Into the Warehouse II 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int maxBoxesInWarehouse(vector<int>& boxes, vector<int>& warehouse) {
    int l = 0;
    int r = warehouse.size() - 1;

    ranges::sort(boxes, greater<>());

    for (const int box : boxes) {
      if (l > r)
        return warehouse.size();
      if (box <= warehouse[l])
        ++l;
      else if (box <= warehouse[r])
        --r;
    }

    return l + (warehouse.size() - r - 1);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) {
    int l = 0;
    int r = warehouse.length - 1;

    boxes = Arrays.stream(boxes)
                .boxed()
                .sorted(Collections.reverseOrder())
                .mapToInt(Integer::intValue)
                .toArray();

    for (final int box : boxes) {
      if (l > r)
        return warehouse.length;
      if (box <= warehouse[l])
        ++l;
      else if (box <= warehouse[r])
        --r;
    }

    return l + (warehouse.length - r - 1);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int:
    l = 0
    r = len(warehouse) - 1

    for box in sorted(boxes, reverse=True):
      if l > r:
        return len(warehouse)
      if box <= warehouse[l]:
        l += 1
      elif box <= warehouse[r]:
        r -= 1

    return l + (len(warehouse) - r - 1)