Apple Redistribution into Boxes
EasyUpdated: Aug 2, 2025
Practice on:
Problem
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 _theminimum 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.
Examples
Example 1
Input: apple = [1,3,2], capacity = [4,3,1,5,2]
Output: 2
Explanation: We will use boxes with capacities 4 and 5.
It is possible to distribute the apples as the total capacity is greater than or equal to the total number of apples.
Example 2
Input: apple = [5,5,5], capacity = [2,4,2,7]
Output: 4
Explanation: We will need to use all the boxes.
Constraints
1 <= n == apple.length <= 501 <= m == capacity.length <= 501 <= apple[i], capacity[i] <= 50- The input is generated such that it's possible to redistribute packs of apples into boxes.
Solution
Method 1 – Greedy Sorting
Intuition
To minimize the number of boxes needed, always use the largest boxes first. By filling the biggest boxes, we can fit more apples quickly, reducing the total number of boxes required.
Approach
- Calculate the total number of apples needed to be distributed:
total = sum(apple). - Sort the
capacityarray in descending order. - Initialize a counter
ans = 0. - Iterate through the sorted capacities:
- For each box, subtract its capacity from
total. - Increment
ansby 1. - Stop when
total <= 0(all apples are distributed).
- Return
ansas the minimum number of boxes needed.
Code
C++
class Solution {
public:
int minimumBoxes(vector<int>& apple, vector<int>& capacity) {
int total = 0;
for (int a : apple) total += a;
sort(capacity.rbegin(), capacity.rend());
int ans = 0;
for (int c : capacity) {
total -= c;
ans++;
if (total <= 0) break;
}
return ans;
}
};
Java
class Solution {
public int minimumBoxes(int[] apple, int[] capacity) {
int total = 0;
for (int a : apple) total += a;
Arrays.sort(capacity);
int ans = 0;
for (int i = capacity.length - 1; i >= 0; i--) {
total -= capacity[i];
ans++;
if (total <= 0) break;
}
return ans;
}
}
Python
class Solution:
def minimumBoxes(self, apple: list[int], capacity: list[int]) -> int:
total: int = sum(apple)
capacity.sort(reverse=True)
ans: int = 0
for c in capacity:
total -= c
ans += 1
if total <= 0:
break
return ans
Complexity
- ⏰ Time complexity:
O(n + m log m)(wherenis length ofapple,mis length ofcapacity) - 🧺 Space complexity:
O(1)(ignoring input storage)