Minimum Limit of Balls in a Bag - Problem

Imagine you're a warehouse manager with bags of balls, and you need to minimize the maximum load in any single bag through strategic splitting operations.

You have an integer array nums where nums[i] represents the number of balls in the i-th bag. You can perform at most maxOperations split operations.

Split Operation: Take any bag containing multiple balls and divide it into two new bags with positive numbers of balls.

Example splits:

  • A bag with 7 balls โ†’ bags with 3 and 4 balls
  • A bag with 5 balls โ†’ bags with 1 and 4 balls, or 2 and 3 balls

Your penalty is the maximum number of balls in any single bag after all operations. Return the minimum possible penalty.

Input & Output

example_1.py โ€” Basic Case
$ Input: nums = [9], maxOperations = 2
โ€บ Output: 3
๐Ÿ’ก Note: Split bag with 9 balls: 9 โ†’ (4,5) โ†’ (4,2,3). Maximum is 4. Then split 4 โ†’ (2,2). Final bags: [2,2,3], maximum is 3.
example_2.py โ€” Multiple Bags
$ Input: nums = [2,4,8,2], maxOperations = 4
โ€บ Output: 2
๐Ÿ’ก Note: Split 8 into smaller pieces: 8 โ†’ (4,4) โ†’ (2,2,2,2). Split one 4: 4 โ†’ (2,2). Final bags have maximum size 2.
example_3.py โ€” No Operations
$ Input: nums = [7,17], maxOperations = 2
โ€บ Output: 7
๐Ÿ’ก Note: With 2 operations: 17 โ†’ (8,9) โ†’ (4,4,9) โ†’ (4,4,4,5). Best we can do is reduce penalty to 7 (from original 7).

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • 1 โ‰ค maxOperations โ‰ค 109
  • 1 โ‰ค nums[i] โ‰ค 109

Visualization

Tap to expand
๐Ÿš› Load: 9๐Ÿš› Load: 7๐Ÿš› Load: 5Before: Penalty = 9Redistribute loads...๐Ÿš› 3๐Ÿš› 3๐Ÿš› 3๐Ÿš› 4๐Ÿš› 5After: Penalty = 5Binary Search Range19mid = 5Check if penalty=5is achievable...โœ“ Yes! Try smaller
Understanding the Visualization
1
Initial State
Heavy trucks with uneven loads
2
Set Target
Binary search for optimal maximum load
3
Check Feasibility
Calculate redistributions needed
4
Find Minimum
Converge to optimal solution
Key Takeaway
๐ŸŽฏ Key Insight: Binary search on the final answer is more efficient than trying all split combinations. Calculate required operations for each penalty candidate instead of simulating splits.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
43.2K Views
Medium-High Frequency
~18 min Avg. Time
1.9K 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