MediumBinary SearchGreedy

1 approach, code in every language

Problem description

You must build an array of exactly n positive integers subject to three rules: every element is at least 1, the absolute difference between any two adjacent elements is at most 1, and the total of all elements does not exceed a given budget maxSum. Among all arrays that satisfy these rules, you want the one whose value at a fixed position index is as large as possible.

Return that largest achievable value at position index.

Example 1

Input: n = 4, index = 2, maxSum = 6

Output: 2

The array [1, 1, 2, 1] uses a total of 5 (within the budget of 6) and places the value 2 at index 2. No valid array can push index 2 higher without breaking a rule.

Example 2

Input: n = 6, index = 1, maxSum = 10

Output: 3

The array [2, 3, 2, 1, 1, 1] sums to 10 and places 3 at index 1, which is the maximum possible peak for that position under the budget.

Constraints

  • 1 <= n <= 10^9
  • 0 <= index < n
  • 1 <= maxSum <= 10^9

After the pattern

Now solve one you haven't seen.

The Tallest Post at a Chosen Place is our own problem on the technique behind Maximum Value at a Given Index in a Bounded Array: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free