Suppose we have three values, n, index and maxSum. Consider an array called nums we have to find nums[index] and nums satisfies the following conditions −
size of nums is n
All elements in n is positive.
|nums[i] - nums[i+1]| <= 1 for all i, 0 <= i < n-1.
The sum of all the elements of nums does not exceed maxSum.
nums[index] is maximized.
So, if the input is like n = 6, index = 3, maxSum = 8, then the output will be 2 because, we can get an array like [1,2,2,2,1,1], that satisfies all conditions, and here nums[3] is maximized.
To solve this, we will follow these steps −
left := quotient of maxSum/n, right := maxSum + 1
ans := 0
while left < right, do
mid := left + quotient of (right-left)/2
ind_l := (mid-1 + maximum of 1 and (mid-index)) * quotient of (minimum of index and (mid-1) /2 + |minimum of 0, mid-index-1|
ind_r = (mid + maximum of 1 and (mid-(n-index-1))) * quotient of (minimum of (n-index) and mid)/2 + |minimum of 0 and (mid-(n-index-1)-1)|
if ind_l + ind_r <= maxSum, then
ans := mid
left := mid+1
otherwise,
right := mid
return ans
Example
Let us see the following implementation to get better understanding −
def solve(n, index, maxSum): left, right = maxSum//n, maxSum+1 ans = 0 while(left<right): mid = left + (right-left)//2 ind_l = (mid-1+max(1,mid-index))*min(index,mid-1)//2 + abs(min(0,mid-index-1)) ind_r = (mid+max(1,mid-(n-index-1)))*min(n-index, mid)//2+ abs(min(0,mid-(n-index-1)-1)) if ind_l + ind_r <=maxSum: ans = mid left = mid+1 else: right = mid return ans n = 6 index = 3 maxSum = 8 print(solve(n, index, maxSum))
Input
6, 3, 8
Output
2