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

Imagine you're designing a mountain-like array where each element can only differ from its neighbors by at most 1. You need to construct an array of length n where you want to maximize the value at a specific index while keeping the total sum within a given budget.

The Challenge: Given three positive integers n, index, and maxSum, construct an array nums that satisfies:

  • Array has exactly n elements (0-indexed)
  • All elements are positive integers
  • Adjacent elements differ by at most 1: |nums[i] - nums[i+1]| โ‰ค 1
  • Total sum doesn't exceed maxSum
  • nums[index] is maximized

Your goal: Return the maximum possible value at nums[index].

Example: With n=4, index=2, maxSum=6, the optimal array is [1,2,3,2] where nums[2] = 3.

Input & Output

example_1.py โ€” Basic Mountain
$ Input: n=4, index=2, maxSum=6
โ€บ Output: 2
๐Ÿ’ก Note: The optimal array is [1,2,3,2] but sum=8 > 6. So we try [1,1,2,1] with sum=5 โ‰ค 6, giving nums[2]=2. Actually, we can do [1,1,2,2] with sum=6, so answer is 2.
example_2.py โ€” Small Array
$ Input: n=1, index=0, maxSum=10
โ€บ Output: 10
๐Ÿ’ก Note: With only one element, we can make it as large as possible: nums[0]=10, sum=10 โ‰ค 10.
example_3.py โ€” Large Budget
$ Input: n=3, index=1, maxSum=18
โ€บ Output: 7
๐Ÿ’ก Note: The optimal array is [6,7,6] with sum=19 > 18. We try [5,6,5] with sum=16 โ‰ค 18. But we can do better: [6,7,5] has sum=18 โ‰ค 18, so answer is 7.

Constraints

  • 1 โ‰ค n โ‰ค 109
  • 0 โ‰ค index < n
  • 1 โ‰ค maxSum โ‰ค 109
  • All elements must be positive integers
  • Adjacent elements can differ by at most 1

Visualization

Tap to expand
Mountain Peak Optimization StrategyOptimal Mountain Shape:PeakSlope downSlope downindexBinary Search Process:Search Range [1, maxSum]Test mid valueโœ“Sum โ‰ค maxSumTry higherโœ—Sum > maxSumTry lowerExample: n=4, index=2, maxSum=6Try height=3:Array: [1,2,3,2], Sum=8 > 6 โœ—Try height=2:Array: [1,1,2,1], Sum=5 โ‰ค 6 โœ“๐ŸŽฏ Key: Binary search finds maximum height where mountain sum โ‰ค maxSum
Understanding the Visualization
1
Understand the Shape
Optimal array forms mountain: peak at index, slopes down to edges
2
Binary Search Setup
Search range [1, maxSum] for maximum valid peak height
3
Calculate Minimum Sum
For each height, compute minimum sum needed for optimal mountain
4
Adjust Search Range
If sum โ‰ค maxSum, try higher; if sum > maxSum, try lower
Key Takeaway
๐ŸŽฏ Key Insight: The optimal solution uses binary search on the peak height combined with mathematical formulas to calculate the minimum sum for each mountain shape, achieving O(log maxSum) time complexity.
Asked in
Google 28 Amazon 22 Microsoft 18 Meta 15
21.5K Views
Medium Frequency
~18 min Avg. Time
892 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