Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 1580: Put Boxes Into the Warehouse II

ArrayGreedySorting

LeetCode 1580 Solution Explanation

Explanation:

To solve this problem, we can use a two-pointer approach. We will sort both the box sizes and the warehouse heights in non-increasing order. Then, we will iterate through the boxes and warehouse from the largest to the smallest, and try to fit as many boxes as possible into the warehouse.

  1. Sort the box sizes and warehouse heights in non-increasing order.
  2. Initialize pointers i for boxes and j for warehouse at the 0th index.
  3. While both pointers are within bounds, check if the current box can fit in the current warehouse height.
  4. If it fits, increment both pointers.
  5. If it doesn't fit, only increment the box pointer.
  6. Repeat until all boxes are processed.
  7. The number of boxes that can fit into the warehouse is the number of times the box pointer is incremented.

Time Complexity: O(n log n) where n is the maximum of number of boxes or warehouse heights. Space Complexity: O(1)

:

LeetCode 1580 Solutions in Java, C++, Python

class Solution {
    public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) {
        Arrays.sort(boxes);
        Arrays.sort(warehouse);

        int i = 0, j = 0;
        int count = 0;

        while (i < boxes.length && j < warehouse.length) {
            if (boxes[i] <= warehouse[j]) {
                count++;
                i++;
            }
            j++;
        }

        return count;
    }
}

Interactive Code Editor for LeetCode 1580

Improve Your LeetCode 1580 Solution

Use the editor below to refine the provided solution for LeetCode 1580. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems