Python 3074.py
class Solution:
def minimumBoxes(self, apple: List[int], capacity: List[int]) -> int:
result = 0
apples = sum(apple)
for c in sorted(capacity, reverse = True):
result += 1
apples -= c
if apples <= 0:
return result
Difficulty
and has an acceptance rate of about 79% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Greedy
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution class implements a method minimumBoxes that determines the smallest number of boxes required to store a given total number of apples. The method receives two lists: apple, which contains the counts of apples in each group, and capacity, which lists the maximum number of apples each box can hold. By aggregating the total apples and then greedily selecting the largest available box capacities, the algorithm computes the minimal box count needed to accommodate all apples.
Key Steps
The core logic proceeds through three distinct phases: aggregation of the apple count, ordering of box capacities, and iterative consumption of capacity until the apple total is exhausted.
The aggregation step is expressed by the line
apples = sum(apple)
which collapses the potentially many entries in apple into a single integer representing the total number of apples to be stored.
Next, the capacities are sorted in descending order to prioritize the largest boxes first. This is performed by the expression
for c in sorted(capacity, reverse = True):
The sorted function creates a new list ordered from the highest capacity to the lowest, ensuring that each iteration of the loop considers the most spacious box still available.
Within the loop, two operations occur on each iteration. The counter result is incremented to reflect the inclusion of another box, and the current box capacity c is subtracted from the remaining apple count. These actions are captured by
result += 1
apples -= c
Finally, a termination condition checks whether the remaining apples have been fully allocated. When apples becomes zero or negative, the method returns the current value of result, indicating the minimal number of boxes required. The termination logic is
if apples <= 0:
return result
Edge Cases Handled
The algorithm gracefully handles the situation where the total apple count is zero. In that case, the initial apples value is zero, the loop body is never entered, and the method would implicitly return 0 because result remains at its initial value.
When the list capacity contains more boxes than necessary, the early return triggered by the apples <= 0 condition prevents unnecessary iteration over the remaining capacities. This ensures that the method stops as soon as the apple requirement is satisfied, regardless of how many extra boxes are present.
If the capacities include values larger than the total number of apples, the first iteration may already reduce apples to a negative number, causing an immediate return with result equal to 1. This demonstrates that the method correctly accounts for oversized boxes without additional checks.
Performance Optimizations
The primary optimization lies in the use of a descending sort on the capacity list. By arranging capacities from largest to smallest, the algorithm minimizes the number of iterations needed to reach the required apple total, effectively achieving a greedy selection that converges quickly.
Creating the sorted list once before entering the loop avoids repeated sorting or scanning operations during iteration. The loop itself performs only constant-time arithmetic and a simple comparison per box, keeping the per-iteration overhead minimal.
The early exit condition (if apples <= 0: return result) eliminates further processing once the goal is met, preventing wasteful computation on remaining capacities. This short-circuit behavior contributes to overall efficiency, especially when the required number of boxes is small relative to the size of the capacity list.
ELI5 - Simplified Explanation
Imagine a big pile of apples that you need to put into boxes. The first part of the code adds up all the apples to see how many there are in total. The boxes have different sizes, so the code puts the biggest ones first to make space as quickly as possible. Every time a new box is grabbed, it counts as one more box used. Then, it takes the number of apples that fit into that box away from the pile. Once there are no apples left, the process stops.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | Java | C++ | Python | TS | |||
| WalkCCC | Java | C++ | Python | |||||
| leetcode.ca | Java | C++ | Go | Python | Rust | TS | ||
| Progiez | Java | C++ | Python | |||||
| github | charles-wangkai | Java | ||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| varunu28 | Java | |||||||
| withaarzoo | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| varunu28 | Java | |||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 3069: Distribute Elements Into Two Arrays I
- problem 3083: Existence of a Substring in a String and Its Reverse
- problem 3114: Latest Time You Can Obtain After Replacing Characters
- problem 3127: Make a Square with the Same Color
- problem 2513: Minimize the Maximum of Two Arrays
- problem 3070: Count Submatrices with Top-Left Element and Sum Less Than k
- problem 3112: Minimum Time to Visit Disappearing Nodes
- problem 3128: Right Triangles
- problem 2503: Maximum Number of Points From Grid Queries
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality