Suppose we have an array nums where the ith element indicates a bag containing nums[i] number of balls. We also have another value called mx. We can perform the following operation at most mx times −
Select any bag of balls and divide it into two new bags with at least one ball.
Here penalty is the maximum number of balls in a bag.
We have to minimize the penalty after the operations. So finally, we have to find the minimum possible penalty after performing the operations.
So, if the input is like nums = [4,8,16,4], mx = 4, then the output will be 4 because we can perform following operations: Initially we have bags like [4,8,16,4], split bag with 16 balls like [4,8,8,8,4], then for each each bag with 8 balls, divide them into two bags with 4 balls each, so array will be like [4,4,4,8,8,4], then [4,4,4,4,4,8,4] and finally [4,4,4,4,4,4,4,4], so here minimum we have 4 balls, that is the penalty.
To solve this, we will follow these steps −
Define a function helper() . This will take target, mx
if target is same as 0, then
return mx + 1
count := 0
for each num in nums, do
count := count + quotient of (num - 1)/target
return count <= mx
From the main method, do the following
left := maximum of the quotient of (sum of all elements of nums /(size of nums + mx)) and 1
right := maximum of nums
while left < right, do
mid := quotient of (left + right)/2
if helper(mid, mx) is non-zero, then
right := mid
otherwise,
left := mid + 1
return left
Example
Let us see the following implementation to get better understanding −
def helper(target, mx): if target == 0: return mx + 1 count = 0 for num in nums: count += (num - 1) // target return count <= mx def solve(nums, mx): left, right = max(sum(nums) // (len(nums) + mx), 1), max(nums) while left < right: mid = (left + right) // 2 if helper(mid, mx): right = mid else: left = mid + 1 return left nums = [4,8,16,4] mx = 4 print(solve(nums, mx))
Input
[4,8,16,4], 4
Output
4