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 == nnums[i]is a positive integer where0 <= i < nabs(nums[i] - nums[i+1]) <= 1where0 <= i < n-1- The sum of all the elements of
numsdoes not exceedmaxSum 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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code