1580. Put Boxes Into the Warehouse II

https://leetcode.com/problems/put-boxes-into-the-warehouse-ii/

Input: boxes = [1,2,2,3,4], warehouse = [3,4,1,2]
Output: 4

from left, cal the min height

height = [3,3,1,1]

from right, cal max height with min

height = [3,3,1,2]

sort height: [1,2, 3,3]

sort box: [1,2,2,3,4]

put box into height one by one if matches, count++

T:O(nlogn + 2*n + mlogm + n), n - warehouse, m - box..
S: O(n)

from left, cal the min height
height = [3,3,1,1]

from right, cal max height with min
height = [3,3,1,2]

[1, 2, 3, 3] height
[1, 2, 2, 3, 4] box

ๅ› ็‚บๆ˜ฏๅพž้ซ˜ๅบฆๅฐ็š„้–‹ๅง‹ๆ”พ, ๆ”พๅˆฐไนŸๆ˜ฏ้ซ˜ๅบฆๅฐ็š„ warehouse, ๆ‰€ไปฅๆ˜ฏok็š„

origi:3412
after:3312

ๆ‰€ไปฅไปฅ้€™ๅ€‹ไพ‹ๅญไพ†่ชช, ๅพžๅฐ็š„้ซ˜้–‹ๅง‹ๆ”พ้€™ๆจฃๅฐฑๆœƒๆ…ขๆ…ข็™ผๆ•ฃๅ‡บๅŽปๅทฆๅณๆ”พ, ๅฐ็š„ๅ…ˆๅ…ฅ, ๆ‰€ไปฅไนŸไธๆœƒๆœ‰ๅกž่ปŠ็š„ๅ•้กŒ

left   ๅฐ  right 
  3  3  1  2
class Solution {
    public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) {
        int n = warehouse.length;
        int height[] = new int[n];
        
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < n; i++) {
            min = Math.min(min, warehouse[i]);
            height[i] = min;
        } // 3311
        
        min = Integer.MAX_VALUE;
        for (int i = n - 1; i >= 0; i--) {
            min = Math.min(min, warehouse[i]);
            height[i] = Math.max(height[i], min);
        } // 3312

        Arrays.sort(height);
        Arrays.sort(boxes);
        
        int count = 0;
        for (int i = 0; i < n; i++) {
            if (count < boxes.length && boxes[count] <= height[i]) {
                count++;
            }
        }
        return count;
    }
}



greedy

like 1564 leetcode solution 2:

sort box desc, put into it, left can put or put into right

T:O(mlogm + m), m - box..
S: O(1)
class Solution {
    public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) {
        Arrays.sort(boxes);
        
        int left = 0;
        int right = warehouse.length - 1;
        int count = 0;
        for (int i = boxes.length - 1; i >= 0; i--) { // box in desc
            if (left <= right) {
                if (boxes[i] <= warehouse[left]) { // put in left side
                    count++;
                    left++;
                } else if (boxes[i] <= warehouse[right]) { // put in right side
                    count++;
                    right--;
                }
            }
        }
        return count;
    }
}

Last updated