#3074
Apple Redistribution into Boxes
EasyArrayGreedySortingGreedySortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
The optimal approach sorts the box capacities in descending order and uses a greedy strategy to fill the boxes starting from the largest. This ensures we use the least number of boxes needed to accommodate all apples.
⚙️
Algorithm
3 steps- 1Step 1: Calculate the total number of apples from all packs.
- 2Step 2: Sort the box capacities in descending order.
- 3Step 3: Iterate through the sorted capacities, adding boxes until the total capacity meets or exceeds the total apples.
solution.py11 lines
1def min_boxes_optimal(apple, capacity):
2 total_apples = sum(apple)
3 capacity.sort(reverse=True)
4 current_capacity = 0
5 box_count = 0
6 for cap in capacity:
7 current_capacity += cap
8 box_count += 1
9 if current_capacity >= total_apples:
10 return box_count
11 return box_countℹ
Complexity note: The time complexity is O(n log n) due to the sorting step, while the space complexity is O(1) as we are using constant space for variables.
- 1Greedy algorithms often yield optimal solutions for resource allocation problems.
- 2Sorting can simplify the problem by allowing us to make better choices first.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.