Open In App

Put Maximum Number of Boxes Into the Warehouse II

Last Updated : 23 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

You are given two arrays of positive integers, boxes[] and warehouse[]. The boxes array represents the heights of some boxes of unit width, and the warehouse array represents the heights of n rooms in a warehouse, labeled from 0 to n-1 from left to right. The warehouse[i] (0-indexed) is the height of the i-th room.

Boxes are put into the warehouse by the following rules:

  • Boxes cannot be stacked.
  • You can rearrange the order in which boxes are inserted.
  • Boxes can be pushed into the warehouse from either side (left or right).
  • If a box’s height exceeds the height of a room in the warehouse, that box and all subsequent boxes cannot be placed beyond that room.

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

Example:

Input: boxes = {1,2,2,3,4}, warehouse = {3,4,1,2}
Output: 4

Input: boxes = {3,5,5,2}, warehouse = {2,1,3,4,5}
Output: 3

Approach:

First Sort the boxes in descending order because this will make sure that we prioritize placing the taller boxes first, maximizing the space utilization. Then we can use two pointers, left and right, which start at opposite ends of the warehouse. We iterate through the boxes, comparing their heights to the ceiling heights at the left and right positions.

  • If a box fits under the ceiling at the left position, we place it there and move the left pointer one position to the right.
  • If the box doesn’t fit at the left but fits under the ceiling at the right position, we place it there and move the right pointer one position to the left.

If the box doesn’t fit at either end, we cannot place it and move on to the next box.

Step-by-step approach:

  • Sort the boxes in descending order of height.
  • Initialize two pointers, left and right, to the opposite ends of the warehouse. These pointers will help us track the available space at each end.
  • Initialize a count variable to keep track of the number of boxes placed.
  • Iterate through the sorted boxes:
    • Check if the current box can fit under the ceiling at the left end. If it fits, place the box there, increment the count, and move the left pointer one position to the right.
    • If the box doesn’t fit at the left but fits under the ceiling at the right end, place the box there, increment the count, and move the right pointer one position to the left.
    • If the box doesn’t fit at either end, move on to the next box.
    • If the left and right pointers cross, it means no more boxes can be placed.
  • Return the count variable, which represents the maximum number of boxes placed in the warehouse.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to find the maximum number of boxes that can be
// put into the warehouse
int maxBoxes(vector<int>& boxes, vector<int>& warehouse)
{
    // Sort the boxes in descending order of height
    sort(boxes.rbegin(), boxes.rend());

    // Initialize pointers for left and right ends of the
    // warehouse
    int left = 0, right = warehouse.size() - 1;

    // Initialize count of boxes placed
    int count = 0;

    // Iterate through the sorted boxes
    for (int i = 0; i < boxes.size(); i++) {

        // Check if the current box can be placed at the
        // left end
        if (boxes[i] <= warehouse[left]) {
            count++; // Increment count if placed
            left++; // Move left pointer to the right
        }
        // Otherwise, check if the box can be placed at the
        // right end
        else if (boxes[i] <= warehouse[right]) {
            count++; // Increment count if placed
            right--; // Move right pointer to the left
        }

        // If the pointers cross, no more boxes can be
        // placed
        if (left > right) {
            break;
        }
    }

    // Return the maximum number of boxes placed
    return count;
}

int main()
{

    // Define static input boxes and warehouse heights
    vector<int> boxes = { 1, 2, 3, 4 };
    vector<int> warehouse = { 3, 1, 2 };

    // Call the maxBoxes method with the static input
    int result = maxBoxes(boxes, warehouse);

    // Print the maximum number of boxes that can be put in
    // the warehouse
    cout << "The maximum number of boxes that can be put "
            "in the warehouse is "
         << result << "." << endl;

    return 0;
}
Java
import java.util.Arrays;

public class MaxBoxesInWarehouse {
    public static int maxBoxes(int[] boxes, int[] warehouse) {
        // Sort the boxes in descending order of height
        Arrays.sort(boxes);
        Arrays.sort(warehouse);

        // Initialize pointers for left and right ends of the warehouse
        int left = 0, right = warehouse.length - 1;

        // Initialize count of boxes placed
        int count = 0;

        // Iterate through the sorted boxes
        for (int i = boxes.length - 1; i >= 0; i--) {
            // Check if the current box can be placed at the left end
            if (boxes[i] <= warehouse[left]) {
                count++; // Increment count if placed
                left++; // Move left pointer to the right
            }
            // Otherwise, check if the box can be placed at the right end
            else if (boxes[i] <= warehouse[right]) {
                count++; // Increment count if placed
                right--; // Move right pointer to the left
            }

            // If the pointers cross, no more boxes can be placed
            if (left > right) {
                break;
            }
        }

        // Return the maximum number of boxes placed
        return count;
    }

    public static void main(String[] args) {
        // Define static input boxes and warehouse heights
        int[] boxes = { 1, 2, 3, 4 };
        int[] warehouse = { 3, 1, 2 };

        // Call the maxBoxes method with the static input
        int result = maxBoxes(boxes, warehouse);

        // Print the maximum number of boxes that can be put in the warehouse
        System.out.println("The maximum number of boxes that can be put in the warehouse is " + result + ".");
    }
}

// This code is contributed by shivamgupta0987654321
Python3
from typing import List

# Function to find the maximum number of boxes that can be
# put into the warehouse
def max_boxes(boxes: List[int], warehouse: List[int]) -> int:
    # Sort the boxes in descending order of height
    boxes.sort(reverse=True)

    # Initialize pointers for left and right ends of the
    # warehouse
    left, right = 0, len(warehouse) - 1

    # Initialize count of boxes placed
    count = 0

    # Iterate through the sorted boxes
    for box in boxes:
        # Check if the current box can be placed at the
        # left end
        if box <= warehouse[left]:
            count += 1  # Increment count if placed
            left += 1  # Move left pointer to the right
        # Otherwise, check if the box can be placed at the
        # right end
        elif box <= warehouse[right]:
            count += 1  # Increment count if placed
            right -= 1  # Move right pointer to the left

        # If the pointers cross, no more boxes can be
        # placed
        if left > right:
            break

    # Return the maximum number of boxes placed
    return count


# Define static input boxes and warehouse heights
boxes = [1, 2, 3, 4]
warehouse = [3, 1, 2]

# Call the max_boxes method with the static input
result = max_boxes(boxes, warehouse)

# Print the maximum number of boxes that can be put in
# the warehouse
print(f"The maximum number of boxes that can be put in the warehouse is {result}.")
JavaScript
function maxBoxes(boxes, warehouse) {
    // Sort the boxes and warehouse heights arrays
    boxes.sort((a, b) => b - a);
    warehouse.sort((a, b) => a - b);

    // Initialize pointers for left and right ends of the warehouse
    let left = 0, right = warehouse.length - 1;

    // Initialize count of boxes placed
    let count = 0;

    // Iterate through the sorted boxes
    for (let i = 0; i < boxes.length; i++) {
        // Check if the current box can be placed at the left end
        if (boxes[i] <= warehouse[left]) {
            count++; // Increment count if placed
            left++; // Move left pointer to the right
        }
        // Otherwise, check if the box can be placed at the right end
        else if (boxes[i] <= warehouse[right]) {
            count++; // Increment count if placed
            right--; // Move right pointer to the left
        }

        // If the pointers cross, no more boxes can be placed
        if (left > right) {
            break;
        }
    }

    // Return the maximum number of boxes placed
    return count;
}

// Define input boxes and warehouse heights arrays
const boxes = [1, 2, 3, 4];
const warehouse = [3, 1, 2];

// Call the maxBoxes function with the input arrays
const result = maxBoxes(boxes, warehouse);

// Print the maximum number of boxes that can be put in the warehouse
console.log("The maximum number of boxes that can be put in the warehouse is " + result + ".");

Output
The maximum number of boxes that can be put in the warehouse is 3.

Time Complexity: O(nlogn)
Auxiliary space: O(n)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads