Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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
numsis nAll elements in
numsare positive|nums[i] - nums[i+1]| <= 1for all i, where 0 <= i < n-1The sum of all elements of
numsdoes not exceed maxSumnums[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] = midCheck 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.
