#1760

Minimum Limit of Balls in a Bag

Medium
ArrayBinary SearchBinary SearchGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log(max(nums)))
Space
O(1)
O(1)
💡

Intuition

Time O(n log(max(nums)))Space O(1)

The optimal solution uses binary search to efficiently find the minimum possible penalty. By guessing a maximum size and checking if we can achieve that with the allowed operations, we can narrow down our search quickly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Set low to 1 and high to the maximum number of balls in any bag.
  2. 2Step 2: Perform binary search while low is less than or equal to high.
  3. 3Step 3: For each mid value, calculate the number of operations needed to ensure no bag exceeds mid.
  4. 4Step 4: If operations needed are less than or equal to maxOperations, update result and search lower; otherwise, search higher.
solution.py20 lines
1# Full working Python code
2
3def minPenalty(nums, maxOperations):
4    def canAchieve(maxSize):
5        operations = 0
6        for balls in nums:
7            operations += (balls - 1) // maxSize
8        return operations <= maxOperations
9
10    low, high = 1, max(nums)
11    result = high
12    while low <= high:
13        mid = (low + high) // 2
14        if canAchieve(mid):
15            result = mid
16            high = mid - 1
17        else:
18            low = mid + 1
19    return result
20

Complexity note: The time complexity is driven by the binary search over the range of possible maximum sizes (1 to max(nums)), and for each size, we check the number of operations needed, which is O(n).

  • 1Binary search helps efficiently narrow down the possible maximum size of balls in a bag.
  • 2Understanding how to calculate the number of operations needed for a given maximum size is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.