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: Build Optimal MountainInput: n=4, index=2, maxSum=611210123PeakMountain shape: decreases by 1 from peakSum = 1 + 1 + 2 + 1 = 5 ≤ 6 ✓Maximum value at index 2: 2
Understanding the Visualization
1
Input
n=4, index=2, maxSum=6
2
Process
Build mountain with peak at index 2
3
Output
Maximum value 2 at index 2
Key Takeaway
🎯 Key Insight: The optimal array forms a mountain with the peak at the given index, and binary search efficiently finds the maximum valid peak height.
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