Program to find maximum value at a given index in a bounded array in Python

Suppose we have three values: n, index and maxSum. We need to construct an array nums and find the maximum possible value at nums[index] that satisfies the following conditions:

  • Size of nums is n

  • All elements in nums are positive

  • |nums[i] - nums[i+1]| <= 1 for all i, where 0 <= i < n-1

  • The sum of all elements of nums does not exceed maxSum

  • nums[index] is maximized

For example, if n = 6, index = 3, maxSum = 8, then the output will be 2. We can construct an array like [1,2,2,2,1,1] that satisfies all conditions, and nums[3] is maximized to 2.

Algorithm Approach

We use binary search to find the maximum possible value. The key insight is that for a given peak value at the index, we can calculate the minimum sum required and check if it exceeds maxSum:

  • Initialize search range: left = maxSum//n, right = maxSum + 1

  • For each mid value, calculate the minimum sum needed if nums[index] = mid

  • Check if this sum is within the maxSum limit

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
        
        # Calculate minimum sum for left side of index
        ind_l = (mid - 1 + max(1, mid - index)) * min(index, mid - 1) // 2 + abs(min(0, mid - index - 1))
        
        # Calculate minimum sum for right side (including index)
        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

# Test with given example
n = 6
index = 3
maxSum = 8
result = solve(n, index, maxSum)
print(f"Maximum value at index {index}: {result}")

# Let's verify with another example
n = 4
index = 0
maxSum = 10
result2 = solve(n, index, maxSum)
print(f"Maximum value at index {index}: {result2}")
Maximum value at index 3: 2
Maximum value at index 0: 3

How It Works

The algorithm works by:

  • Binary Search: We search for the maximum possible peak value

  • Sum Calculation: For each candidate value, we calculate the minimum sum needed

  • Constraint Check: We verify if the calculated sum fits within maxSum

The complex formulas calculate the minimum sum by considering that values decrease by at most 1 as we move away from the peak index, with a minimum value of 1.

Conclusion

This binary search approach efficiently finds the maximum value at a given index in O(log maxSum) time. The key is calculating the minimum possible sum for each candidate peak value and checking if it satisfies the constraint.

Updated on: 2026-03-26T14:37:16+05:30

448 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements