Maximum Value at a Given Index in a Bounded Array - Problem

You are given three positive integers: n, index, and maxSum. You want to construct an array nums (0-indexed) that satisfies the following conditions:

  • nums.length == n
  • nums[i] is a positive integer where 0 <= i < n
  • abs(nums[i] - nums[i+1]) <= 1 where 0 <= i < n-1
  • The sum of all the elements of nums does not exceed maxSum
  • nums[index] is maximized

Return nums[index] of the constructed array.

Note: abs(x) equals x if x >= 0, and -x otherwise.

Input & Output

Example 1 — Basic Case
$ Input: n = 4, index = 2, maxSum = 6
Output: 2
💡 Note: The optimal array is [1,1,2,1]. The peak value 2 at index 2 satisfies all constraints: adjacent differences ≤ 1, sum = 5 ≤ 6, and 2 is maximized.
Example 2 — Edge Position
$ Input: n = 6, index = 1, maxSum = 10
Output: 3
💡 Note: The optimal array is [2,3,2,1,1,1]. Peak at index 1 has value 3, sum = 10 ≤ 10, adjacent differences ≤ 1.
Example 3 — Minimum Sum
$ Input: n = 3, index = 0, maxSum = 3
Output: 1
💡 Note: With minimum possible sum, the array is [1,1,1]. Peak at index 0 has value 1, sum = 3 = maxSum.

Constraints

  • 1 ≤ n ≤ 109
  • 0 ≤ index < n
  • 1 ≤ maxSum ≤ 109

Visualization

Tap to expand
Maximum Value at Given Index in Bounded Array INPUT Array to construct (n=4): ? ? ? ? i=0 i=1 i=2 i=3 target index n = 4 index = 2 maxSum = 6 |nums[i]-nums[i+1]| <= 1 Constraints: All elements positive Sum <= maxSum Maximize nums[index] ALGORITHM STEPS 1 Binary Search Setup lo=1, hi=maxSum=6 2 Calculate Sum For mid value, compute total array sum 3 Sum Formula Left + Right sides with arithmetic series 4 Adjust Search sum <= maxSum: lo=mid+1 else: hi=mid-1 Binary Search Progress: mid=3: sum=1+2+3+2=8 > 6 mid=2: sum=1+2+2+1=6 <= 6 Result: 2 (valid) OK FINAL RESULT Constructed Array: 1 2 2 1 i=0 i=1 i=2 i=3 OUTPUT 2 Verification: Sum: 1+2+2+1 = 6 <= 6 OK |1-2|=1, |2-2|=0, |2-1|=1 OK All elements positive OK nums[2] = 2 (maximized) OK Key Insight: Use binary search on the value at index. For each candidate value, calculate the minimum possible sum using arithmetic series (values decrease by 1 going away from index, minimum is 1). Time: O(log(maxSum)) | Space: O(1) - Binary search makes this optimal! TutorialsPoint - Maximum Value at a Given Index in a Bounded Array | Binary Search Approach
Asked in
Google 15 Microsoft 12
23.4K Views
Medium Frequency
~25 min Avg. Time
876 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen