<p>You are given three positive integers:&nbsp;<code>n</code>, <code>index</code>, and <code>maxSum</code>. You want to construct an array <code>nums</code> (<strong>0-indexed</strong>)<strong> </strong>that satisfies the following conditions:</p>

<ul>
	<li><code>nums.length == n</code></li>
	<li><code>nums[i]</code> is a <strong>positive</strong> integer where <code>0 &lt;= i &lt; n</code>.</li>
	<li><code>abs(nums[i] - nums[i+1]) &lt;= 1</code> where <code>0 &lt;= i &lt; n-1</code>.</li>
	<li>The sum of all the elements of <code>nums</code> does not exceed <code>maxSum</code>.</li>
	<li><code>nums[index]</code> is <strong>maximized</strong>.</li>
</ul>

<p>Return <code>nums[index]</code><em> of the constructed array</em>.</p>

<p>Note that <code>abs(x)</code> equals <code>x</code> if <code>x &gt;= 0</code>, and <code>-x</code> otherwise.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> n = 4, index = 2,  maxSum = 6
<strong>Output:</strong> 2
<strong>Explanation:</strong> nums = [1,2,<u><strong>2</strong></u>,1] is one array that satisfies all the conditions.
There are no arrays that satisfy all the conditions and have nums[2] == 3, so 2 is the maximum nums[2].
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 6, index = 1,  maxSum = 10
<strong>Output:</strong> 3
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= maxSum &lt;= 10<sup>9</sup></code></li>
	<li><code>0 &lt;= index &lt; n</code></li>
</ul>

class Solution:
    def maxValue(self, n: int, index: int, maxSum: int) -> int:
        r = n - index - 1 # how many indices are to be filled before the given index
        l = index # how many indices are to be filled after the given index
        start, end = 0, maxSum
        ans = 1 # if in case the given index is zero, we can maximize the index value by 1
        while start <= end:
            mid = (start + end)//2
            sm = mid
            lsum, rsum = 0, 0
            m = mid - 1
            #calculation the sum before the mid index
            if r<=m: rsum = m*(m+1)//2 - (m-r)*(m-r+1)//2
            else: rsum = m*(m+1)//2 + r-m
            #calculating the sum after the mid index
            if l<=m: lsum = m*(m+1)//2 - (m-l)*(m-l+1)//2
            else: lsum = m*(m+1)//2 + l-m

            sm += lsum + rsum 
            #if the value of the total sum is less than maxSum, update the boundaries we're working with 
            if sm <= maxSum:
                ans = mid
                start = mid+1
            else: end = mid - 1
        return ans
26