Skip to main content
Back to problems
#1580
Medium Algorithms

Put boxes into the warehouse ii

Array Greedy Sorting
65.9% acceptance
Mar 31, 2026
228
12

No description available.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_boxes_in_warehouse(mut boxes: Vec<i32>, warehouse: Vec<i32>) -> i32 {
    boxes.sort_unstable_by(|a, b| b.cmp(a)); // sort descending
    let n = warehouse.len();
    let mut left = 0usize;
    let mut right = n - 1;
    let mut count = 0;
    for &b in &boxes {
      if left > right { break; }
      if b <= warehouse[left] {
        count += 1;
        left += 1;
      } else if b <= warehouse[right] {
        count += 1;
        if right == 0 { break; }
        right -= 1;
      }
    }
    count
  }
}