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

1
2
3
4
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

1
2
3
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 <= 50
  • 1 <= m == capacity.length <= 50
  • 1 <= 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:

  1. Calculate the total number of apples needed to be distributed: total = sum(apple).
  2. Sort the capacity array in descending order.
  3. Initialize a counter ans = 0.
  4. Iterate through the sorted capacities:
  • For each box, subtract its capacity from total.
  • Increment ans by 1.
  • Stop when total <= 0 (all apples are distributed).
  1. Return ans as the minimum number of boxes needed.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
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;
   }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
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;
   }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
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) (where n is length of apple, m is length of capacity)
  • 🧺 Space complexity: O(1) (ignoring input storage)