You are given three positive integers n, index, and max_sum. You want to construct an array nums (0-indexed) that satisfies all of the following conditions:
-
nums.length == n
-
nums[i]
is a positive integer for every
0 <= i < n
.
-
abs(nums[i] - nums[i + 1]) <= 1
for every
0 <= i < n - 1
.
-
The sum of all elements of
nums
does not exceed
max_sum
.
-
nums[index]
is as large as possible.
Return nums[index] of the constructed array.
Function Signature
def max_value(n: int, index: int, max_sum: int) -> int:
Rules
-
Return only the value at
index
. Several arrays can reach the maximum, but the maximum value itself is unique.
-
abs(x)
is
x
when
x >= 0
and
-x
otherwise.
Constraints
-
1 <= n <= 10^9
-
0 <= index < n
-
n <= max_sum <= 10^9
, so an array of all 1s always fits and a valid array exists.
Examples
Input: n = 4, index = 2, max_sum = 6
Output: 2
nums = [1,2,2,1] has sum 6 and nums[2] = 2. A value of 3 at index 2 forces at least [1,2,3,2], which sums to 8.
Input: n = 6, index = 1, max_sum = 10
Output: 3
nums = [2,3,2,1,1,1] sums to exactly 10. Raising nums[1] to 4 forces at least [3,4,3,2,1,1], which sums to 14.
Input: n = 5, index = 0, max_sum = 9
Output: 3
[3,2,1,1,1] sums to 8 and leaves 1 unused. A value of 4 at index 0 needs at least [4,3,2,1,1], which sums to 11, so the spare unit cannot be spent on the target cell.