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
|
|
Example 2
|
|
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:
- Calculate the total number of apples needed to be distributed:
total = sum(apple)
. - Sort the
capacity
array in descending order. - Initialize a counter
ans = 0
. - 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).
- Return
ans
as the minimum number of boxes needed.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n + m log m)
(wheren
is length ofapple
,m
is length ofcapacity
) - 🧺 Space complexity:
O(1)
(ignoring input storage)