5711. The maximum value at the specified subscript in a bounded array

Ideas

First of all, it is easy to think that the answer is monotonic.
So the approach is to split the answer.
When a[index]=mid, if the sum of the entire sequence is less than or equal to maxSum, then if a[index]<mid, it must be satisfied.
Then we try to increase mid, if it meets the lower limit of increase, if not, decrease the upper limit.

According to the conditions of the question, pay attention to the two points
1. Both are positive integers
2. The difference between two adjacent ones is at most 1

Then we know that the current a[index]=mid is to make this position as the most value point as much as possible, and other positions as small as possible.
Let's calculate the left part, and you can put index+1 numbers on the left (including the position of index).
In fact, it just keeps decreasing to the left.
If it is reduced to 1, because it needs to be a positive integer, the remaining positions are still 1s.

The right side is calculated in the same way.

Code

class Solution {
    
    
public:
    int maxValue(int n, int index, int maxSum) {
    
    
            int L=index+1,R=n-index;
            int l=0,r=1e9+1;
            while(l+1<r){
    
    
                int mid=l+r>>1;
                long long ans=0;
                if(L>=mid) ans+=1ll*mid*(mid+1)/2+L-mid;//能放的个数≥mid  剩下位置放1
                else ans+=1ll*L*(mid+mid-L+1)/2;//减不到1,即求[mid-L+1,mid]这个区间的和
                //下面右部分同理
                if(R>=mid) ans+=1ll*mid*(mid+1)/2+R-mid;
                else ans+=1ll*R*(mid+mid-R+1)/2;
                ans-=mid;
                if(ans<=maxSum) l=mid;
                else r=mid;

            }
        return l;
    }
};

Guess you like

Origin blog.csdn.net/qq_43563669/article/details/115047723