Apple Redistribution into Boxes - 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 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.

Input & Output

Example 1 — Basic Case
$ Input: apple = [1,3,2], capacity = [4,3,1,5,2]
Output: 2
💡 Note: We need 1+3+2 = 6 apples total. Using boxes with capacity [5,4] gives us 9 capacity, which is enough. We need minimum 2 boxes.
Example 2 — Single Large Box
$ Input: apple = [5,5,5], capacity = [2,4,2,7]
Output: 4
💡 Note: Total apples = 15. Even the largest box (7) isn't enough alone. We need all boxes: 2+4+2+7 = 15.
Example 3 — Perfect Fit
$ Input: apple = [1,1,1,1,1], capacity = [10]
Output: 1
💡 Note: Total apples = 5. Single box with capacity 10 is more than enough.

Constraints

  • 1 ≤ n, m ≤ 50
  • 1 ≤ apple[i] ≤ 50
  • 1 ≤ capacity[i] ≤ 50

Visualization

Tap to expand
Apple Redistribution into Boxes INPUT Apple Packs (n=3) 1 3 2 Total: 1+3+2 = 6 apples Box Capacities (m=5) 4 3 1 5 2 apple = [1,3,2] capacity = [4,3,1,5,2] Find min boxes needed to hold all 6 apples ALGORITHM STEPS 1 Sum all apples total = 1+3+2 = 6 2 Sort capacities DESC [5,4,3,2,1] 5 4 3 2 1 3 Greedy selection Pick largest boxes first Box 1 (cap=5): sum=5 5 < 6 Box 2 (cap=4): sum=9 9 >= 6 STOP! We have enough! 4 Return count boxes_used = 2 FINAL RESULT Selected Boxes Box 1 Cap: 5 Box 2 Cap: 4 5 apples + 1 apple = 6 total Output: 2 OK - Minimum boxes! Total capacity: 5+4 = 9 Needed: 6 apples 9 >= 6 (sufficient) Key Insight: The greedy approach works because we want to minimize the number of boxes. By always selecting the largest available box first, we maximize capacity per selection, reaching our total fastest. TutorialsPoint - Apple Redistribution into Boxes | Greedy - Largest Boxes First Time: O(n + m log m) | Space: O(1)
Asked in
Apple 15 Google 12 Amazon 8
24.6K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen