LeetCode 1564: Put Boxes Into the Warehouse I Solution

Master LeetCode problem 1564 (Put Boxes Into the Warehouse I), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1564. Put Boxes Into the Warehouse I

Problem Explanation

Explanation

Given the heights of the boxes and the heights of the warehouse shelves, the task is to find the maximum number of boxes that can be put into the warehouse from left to right while respecting the height constraints.

To solve this problem, we can sort the heights of the boxes and the heights of the shelves in non-increasing order. Then, we can iterate from left to right and try to place each box in the warehouse at the lowest possible shelf height that can accommodate it. We can use two pointers to keep track of the current box and the current shelf being considered.

Algorithm:

  1. Sort the box heights and shelf heights in non-increasing order.
  2. Initialize two pointers, one for the current box and one for the current shelf.
  3. Iterate through the boxes:
    • If the current box height is less than or equal to the current shelf height, increment the count of boxes placed and move to the next box and the next shelf.
    • If the current box height is greater than the current shelf height, move to the next shelf.
  4. Return the count of boxes placed.

Time complexity: O(nlogn) where n is the number of boxes or shelves. Space complexity: O(1) as we are using constant extra space.

Solution Code

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

        int count = 0;
        int boxIdx = 0;
        int shelfIdx = warehouse.length - 1;

        while (boxIdx < boxes.length && shelfIdx >= 0) {
            if (boxes[boxIdx] <= warehouse[shelfIdx]) {
                count++;
                boxIdx++;
            }
            shelfIdx--;
        }

        return count;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1564 (Put Boxes Into the Warehouse I)?

This page provides optimized solutions for LeetCode problem 1564 (Put Boxes Into the Warehouse I) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1564 (Put Boxes Into the Warehouse I)?

The time complexity for LeetCode 1564 (Put Boxes Into the Warehouse I) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1564 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1564 in Java, C++, or Python.

Back to LeetCode Solutions