Python 1760.py
class Solution:
def minimumSize(self, nums: List[int], maxOperations: int) -> int:
# steps required to split each bag such that it fits the maximum size
def steps(size):
result = 0
for n in nums:
if n > size:
# break down each oversized bag into bags of size "size"
smaller = ceil(n / size)
result += smaller - 1
return result
left = 1
right = max(nums)
while left != right:
mid = (left + right) // 2
if steps(mid) > maxOperations:
left = mid + 1
else:
right = mid
return left
Difficulty
and has an acceptance rate of about 66% (200k+ submissions).
Typical patterns to solve this problem:
- Array
- Binary Search
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 implementation solves the problem of determining the smallest possible maximum bag size after performing at most a given number of split operations on an array of bag volumes. It does this by repeatedly checking whether a candidate size can be achieved within the allowed number of operations and narrowing the search space until the optimal size is found.
Key Steps
Helper that counts required operations
def steps(size):
result = 0
for n in nums:
if n > size:
smaller = ceil(n / size)
result += smaller - 1
return result
The inner function iterates over every element in the input list. For each bag larger than the candidate size, it computes how many sub-bags are needed (ceil(n / size)) and adds the number of splits required (smaller - 1) to a running total. The final total represents the minimum number of operations needed to ensure no bag exceeds size.
Setting the binary-search bounds
left = 1
right = max(nums)
The search interval is initialized with the smallest feasible size (1) and the largest existing bag size (max(nums)). This guarantees that the answer lies somewhere within the interval.
Binary-search loop that converges on the answer
while left != right:
mid = (left + right) // 2
if steps(mid) > maxOperations:
left = mid + 1
else:
right = mid
During each iteration the midpoint of the current interval is examined. The helper steps determines how many operations would be required to achieve that midpoint as the maximum bag size. If the required operations exceed the allowed limit, the lower bound is moved just above mid; otherwise the upper bound is moved down to mid. The loop terminates when the lower and upper bounds meet, indicating that the smallest feasible size has been isolated.
Returning the minimal feasible size
return left
At termination left (which equals right) holds the minimal maximum bag size that can be achieved with at most maxOperations splits, and this value is returned as the final result.
Edge Cases Handled
When every bag already fits within the candidate size, the helper function adds nothing to the operation count, allowing the binary search to quickly converge to the current maximum bag size. If maxOperations is zero, the algorithm effectively searches for the smallest size that requires no splits, which will be the original maximum element. The lower bound of 1 ensures that even the extreme case where all bags consist of a single unit is considered, preventing an infinite loop. The use of ceil guarantees correct rounding up for division, handling cases where a bag size is not an exact multiple of the candidate size.
Performance Optimizations
The algorithm leverages binary search to reduce the number of candidate sizes examined from linear in the range of bag values to logarithmic, dramatically cutting the number of calls to the steps helper. Inside steps, the computation ceil(n / size) is performed using integer arithmetic, avoiding floating-point overhead. By accumulating the required operations in a single pass over nums and exiting the loop only after all elements are processed, the implementation minimizes redundant work. The early decision in the binary-search loop-moving the bounds based on a single comparison-prevents unnecessary further evaluation of sizes that are already known to be infeasible.
ELI5 - Simplified Explanation
Imagine there are several bags filled with marbles. Some bags are huge and some are tiny. A game needs these bags to be small enough so that no bag has more marbles than a certain limit. There is only a small number of times allowed to split a big bag into two smaller ones.
To solve this, the code acts like it is testing out different size limits to see which one works best. It starts by picking a middle size between the smallest possible bag and the biggest bag. Then, it looks at every bag of marbles. If a bag is bigger than the middle size, it figures out how many times that bag needs to be split to make all the pieces fit the limit. It adds up all those splits to see if they fit within the allowed number of operations.
If the total number of splits is too high, it means the size limit was too small, so it tries a larger size. If the total number of splits works out, it remembers that size and tries to see if an even smaller size could also work. By doing this over and over, it slowly zooms in until it finds the smallest possible size that still fits within the rules.
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 | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Python | Java | |||||||
| leetcode.ca | C++ | JS | Python | Java | C# | Go | Rust | TS | ||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JS | |||||||||
| lkwq007 | Python | |||||||||
| Shamik07 | Dart | |||||||||
| suxrobGM | C# | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Python, Java | |||||||||
| leetcode.ca | C++, C#, Go, Java, JavaScript, Python, Rust, TypeScript | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| haoel | C++ | |||||||||
| JoshCrozier | JavaScript | |||||||||
| lkwq007 | Python | |||||||||
| Shamik07 | Dart | |||||||||
| suxrobGM | C# |
Videos
Similar Problems
- problem 2064: Minimized Maximum of Products Distributed to Any Store
Solved On The Same Day
- problem 2529: Maximum Count of Positive Integer and Negative Integer
- problem 532: K-diff Pairs in an Array
- problem 718: Maximum Length of Repeated Subarray
- problem 826: Most Profit Assigning Work
- problem 1237: Find Positive Integer Solution for a Given Equation
- problem 1283: Find the Smallest Divisor Given a Threshold
- problem 1552: Magnetic Force Between Two Balls
- problem 1561: Maximum Number of Coins You Can Get
- problem 1870: Minimum Speed to Arrive on Time
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