Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

1760. Minimum Limit of Balls in a Bag

ArrayBinary Search

Explanation:

To solve this problem, we can use binary search to find the minimum penalty. We can start with a lower bound of 1 (minimum number of balls in a bag) and an upper bound of the maximum number of balls in any bag. We iterate through the binary search until the lower bound is less than or equal to the upper bound. For each mid value, we calculate the number of operations needed to split the bags such that the maximum number of balls in a bag is less than or equal to mid. If the number of operations needed is less than or equal to the given maxOperations, we update the upper bound. Otherwise, we update the lower bound.

At the end of the binary search, the lower bound will be the minimum penalty required.

  • Time complexity: O(n log(max(balls)))
  • Space complexity: O(1)

:

class Solution {
    public int minimumSize(int[] nums, int maxOperations) {
        int left = 1, right = (int)1e9;
        
        while (left < right) {
            int mid = left + (right - left) / 2;
            int ops = 0;
            for (int num : nums) {
                ops += (num - 1) / mid;
            }
            if (ops > maxOperations) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        
        return left;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.