Minimum Limit of Balls in a Bag - Problem

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

You can perform the following operation at most maxOperations times:

  • Take any bag of balls and divide it into two new bags with a positive number of balls.
  • For example, a bag of 5 balls can become two new bags of 1 and 4 balls, or two new bags of 2 and 3 balls.

Your penalty is the maximum number of balls in a bag. You want to minimize your penalty after the operations.

Return the minimum possible penalty after performing the operations.

Input & Output

Example 1 — Basic Case
$ Input: nums = [9], maxOperations = 2
Output: 3
💡 Note: Split bag of 9 balls: 9 → 6,3 → 3,3,3. Penalty is max(3,3,3) = 3.
Example 2 — Multiple Bags
$ Input: nums = [2,4,8,2], maxOperations = 4
Output: 2
💡 Note: Split 8 into 4,4, then each 4 into 2,2. Result: [2,4,2,2,2,2,2]. Max penalty = 4, but we can do better by splitting the 4 too for penalty 2.
Example 3 — No Operations Needed
$ Input: nums = [1,2,3], maxOperations = 5
Output: 3
💡 Note: Already optimal - max is 3 and we don't need any operations.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ maxOperations ≤ 109
  • 1 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Limit of Balls in a Bag INPUT 9 balls nums = [9] maxOperations = 2 Goal: Minimize max bag size 9 Initial penalty: 9 ALGORITHM STEPS 1 Binary Search Setup Range: [1, 9] (penalty) 2 Check mid = 5 ops = ceil(9/5)-1 = 1 1 <= 2, OK! Try smaller 3 Check mid = 3 ops = ceil(9/3)-1 = 2 2 <= 2, OK! Try smaller 4 Check mid = 2 ops = ceil(9/2)-1 = 4 4 > 2, Too many ops! Binary Search Progress: [1...........9] mid=5 [1.....5] mid=3 [1..3] mid=2 [3] --> Answer: 3 FINAL RESULT After 2 operations: 9 Op 1 6 3 Op 2 3 3 3 3 bags of 3 balls each Min Penalty 3 Key Insight: Binary search on the answer! For a target penalty P, we need ceil(balls/P) - 1 operations per bag. If total ops <= maxOperations, penalty P is achievable. Search for minimum achievable P. Time: O(n * log(max)) | Space: O(1) TutorialsPoint - Minimum Limit of Balls in a Bag | Binary Search Approach
Asked in
Amazon 23 Google 15 Microsoft 12
68.4K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen