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
classSolution {publicintmaxBoxesInWarehouse(int[] boxes,int[] warehouse) {int n =warehouse.length;int height[] =newint[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); } // 3312Arrays.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)
classSolution {publicintmaxBoxesInWarehouse(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 descif (left <= right) {if (boxes[i] <= warehouse[left]) { // put in left side count++; left++; } elseif (boxes[i] <= warehouse[right]) { // put in right side count++; right--; } } }return count; }}