Maximum Value at a Given Index in a Bounded Array

Build a length-n positive-integer array with adjacent diff ≤ 1, total sum ≤ maxSum — binary search the peak.

Medium
Time O(log maxSum) Space O(1)
LeetCode
5 min read
binary-search math

Problem#

Build an array of n positive integers where adjacent diff ≤ 1, sum ≤ maxSum, and index-th value is maximized. Return that max value.

Examples#

  • n = 4, index = 2, maxSum = 62
  • n = 6, index = 1, maxSum = 103

Constraints#

  • 1 <= n <= maxSum <= 10^9.

Hints#

Hint 1
For a candidate peak v, the minimum sum is a triangular shape: descend by 1 each side until hitting 1, then a flat tail of 1s.

Approach#

Binary search on the peak. For candidate v at position index, compute the minimum sum: left side descends to 1 over index steps, right side descends to 1 over n - 1 - index steps. Use the closed-form for sums of arithmetic sequences (and flat 1-tails when the slope hits 1 early). Find the largest v with sum ≤ maxSum.

Solution#

Max Value at Index in Bounded Array
class Solution {
public:
int maxValue(int n, int index, int maxSum) {
auto sideSum = [](long long v, long long len) {
if (v >= len) return (v + v - len + 1) * len / 2; // v, v-1, ..., v-len+1
return (v + 1) * v / 2 + (len - v); // v, ..., 1, 1, ..., 1
};
auto totalSum = [&](long long v) {
return v + sideSum(v - 1, index) + sideSum(v - 1, n - 1 - index);
};
long long lo = 1, hi = maxSum;
while (lo < hi) {
long long mid = lo + (hi - lo + 1) / 2;
if (totalSum(mid) <= maxSum) lo = mid;
else hi = mid - 1;
}
return (int)lo;
}
};

Editorial#

The minimum-sum shape for a given peak is a tent: descend by 1 from the peak in each direction until reaching 1, then 1s thereafter. The two closed-form cases handle “slope reaches base length” vs “slope clips at 1”. Upper-bound flavor (mid + 1) — note the mid = lo + (hi - lo + 1) / 2 rounding to avoid infinite loop.

Complexity#

  • Time: O(log maxSum).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.