Skip to main content
Back to problems
#3074
Easy Algorithms

Apple redistribution into boxes

Array Greedy Sorting
78.5% acceptance
Feb 25, 2026
408
24
You are given an array apple of size n and an array capacity of size m. There are n packs where the ith pack contains apple[i] apples. There are m boxes as well, and the ith box has a capacity of capacity[i] apples. Return the minimum number of boxes you need to select to redistribute these n packs of apples into boxes. Note that, apples from the same pack can be distributed into different boxes.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn minimum_boxes(apple: Vec<i32>, capacity: Vec<i32>) -> i32 {
    let total: i32 = apple.iter().sum();
    let mut cap = capacity.clone();
    cap.sort_unstable_by(|a, b| b.cmp(a));
    let mut sum = 0;
    for (i, &c) in cap.iter().enumerate() {
      sum += c;
      if sum >= total { return (i + 1) as i32; }
    }
    cap.len() as i32
  }
}