#1802
Maximum Value at a Given Index in a Bounded Array
MediumMathBinary SearchGreedyBinary SearchGreedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(log(maxSum) * n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(log(maxSum) * n)Space O(1)
Instead of generating arrays, we can use binary search to find the maximum possible value for nums[index] that satisfies the conditions, leveraging the constraints to minimize the sum.
⚙️
Algorithm
3 steps- 1Step 1: Define a binary search range from 1 to maxSum.
- 2Step 2: For each mid value in the binary search, calculate the minimum sum required to create a valid array with nums[index] = mid.
- 3Step 3: If the calculated sum is less than or equal to maxSum, it means we can potentially increase mid; otherwise, decrease it.
solution.py14 lines
1def maxValue(n, index, maxSum):
2 def canConstruct(target):
3 left = max(0, target - index)
4 right = max(0, target - (n - index - 1))
5 total = (target * (target + 1)) // 2 - (left * (left + 1)) // 2 - (right * (right + 1)) // 2
6 return total <= maxSum
7 low, high = 1, maxSum
8 while low < high:
9 mid = (low + high + 1) // 2
10 if canConstruct(mid):
11 low = mid
12 else:
13 high = mid - 1
14 return lowℹ
Complexity note: The binary search runs in logarithmic time relative to maxSum, and for each mid value, we calculate the sum in linear time, leading to an overall efficient complexity.
- 1The maximum value at the given index is constrained by the total sum allowed and the adjacent values.
- 2Using binary search allows us to efficiently narrow down the maximum possible value without generating all possible arrays.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.