LeetCode-in-Java

1760. Minimum Limit of Balls in a Bag

Medium

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:

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.

Example 1:

Input: nums = [9], maxOperations = 2

Output: 3

Explanation:

Example 2:

Input: nums = [2,4,8,2], maxOperations = 4

Output: 2

Explanation:

Example 3:

Input: nums = [7,17], maxOperations = 2

Output: 7

Constraints:

Solution

public class Solution {
    public int minimumSize(int[] nums, int maxOperations) {
        int left = 1;
        int right = 1_000_000_000;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (operations(nums, mid) > maxOperations) {
                left = mid + 1;
            } else {
                right = mid;
            }
        }
        return left;
    }

    private int operations(int[] nums, int mid) {
        int operations = 0;
        for (int num : nums) {
            operations += (num - 1) / mid;
        }
        return operations;
    }
}