首页 > 其他分享 >1802. 有界数组中指定下标处的最大值

1802. 有界数组中指定下标处的最大值

时间:2023-01-04 21:48:04浏览次数:76  
标签:index 下标 1802 int 最大值 mid maxSum

1802. 有界数组中指定下标处的最大值

class Solution {
    public int maxValue(int n, int index, int maxSum) {
        int l = 1, r = (int) 1e9;
        while (l < r) {
            int mid = (l + r + 1) >> 1;
            if (valid(mid, n, index, maxSum)) l = mid ;
            else r = mid - 1;
        }
        return l;
    }

    public boolean valid(int mid, int n, int index, int maxSum) {
        int left = index;
        int right = n - index - 1;
        return mid + cal(mid, left) + cal(mid, right) <= maxSum;
    }

    public long cal(int big, int length) {
        if (length + 1 < big) {
            int small = big - length;
            return (long) (big - 1 + small) * length / 2;
        } else {
            int ones = length - (big - 1);
            return (long) big * (big - 1) / 2 + ones;
        }
    }
}

标签:index,下标,1802,int,最大值,mid,maxSum
From: https://www.cnblogs.com/eiffelzero/p/17026071.html

相关文章