Minimum Limit of Balls in a Bag — LeetCode 1760 Python Solution

MediumArrayBinary Search
Problem
#1760
Reading time
2 min

The problem

You are given an integer array nums where the ith bag contains nums[i] balls. You are also given an integer maxOperations.

Example

Input
nums = [9], maxOperations = 2
Output
3
Explanation
- Divide the bag with 9 balls into two bags of sizes 6 and 3. [9] -> [6,3].

Python solution

Python
class Solution:
    def minimumSize(self, nums: List[int], maxOperations: int) -> int:
        def check(mx: int) -> bool:
            return sum((x - 1) // mx for x in nums) <= maxOperations

        return bisect_left(range(1, max(nums) + 1), True, key=check) + 1

Complexity

MeasureComplexity
TimeO(n \times \log M), where n and M are the length and the maximum value of the array \textit{nums}, respectively
SpaceO(1) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1760. Minimum Limit of Balls in a Bag is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1760. Minimum Limit of Balls in a Bag?
LeetCode 1760. Minimum Limit of Balls in a Bag is rated Medium on LeetCode.
What is the time complexity of LeetCode 1760. Minimum Limit of Balls in a Bag?
The Python solution on this page runs in O(n \times \log M), where n and M are the length and the maximum value of the array \textit{nums}, respectively.
What is the space complexity of LeetCode 1760. Minimum Limit of Balls in a Bag?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1760. Minimum Limit of Balls in a Bag cover?
LeetCode 1760. Minimum Limit of Balls in a Bag is tagged Array and Binary Search on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview