LeetCode in Kotlin

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

class Solution {
    fun minimumSize(nums: IntArray, maxOperations: Int): Int {
        var left = 1
        var right = 1000000000
        while (left < right) {
            val mid = left + (right - left) / 2
            if (operations(nums, mid) > maxOperations) {
                left = mid + 1
            } else {
                right = mid
            }
        }
        return left
    }

    private fun operations(nums: IntArray, mid: Int): Int {
        var operations = 0
        for (num in nums) {
            operations += (num - 1) / mid
        }
        return operations
    }
}