---
# System prepended metadata

title: 1580. Put Boxes Into the Warehouse II
tags: [Leetcode, Two Pointers, Sorting, Medium, Greedy]

---

# 1580. Put Boxes Into the Warehouse II
###### tags: `Leetcode` `Medium` `Greedy` `Sorting` `Two Pointers`
Link: https://leetcode.com/problems/put-boxes-into-the-warehouse-ii/description/
## 思路
放进去的box高度从两边到中间只能是递减关系
因此我们先排序box
然后双指针 一个指左端点 一个指右端点
把高度比较高的box先排进去
## Code
```java=
class Solution {
    public int maxBoxesInWarehouse(int[] boxes, int[] warehouse) {
        Arrays.sort(boxes);
        int n = warehouse.length;
        int p1 = 0, p2 = n-1;
        int ans = 0;
        for(int i=boxes.length-1; i>=0 && p1<=p2; i--){
            if(boxes[i]<=warehouse[p1]){
                p1++;
                ans++;
            }
            else if(boxes[i]<=warehouse[p2]){
                p2--;
                ans++;
            }
        }
        return ans;
    }
}
```