其他分享
首页 > 其他分享> > 【2302. 统计得分小于 K 的子数组数目】前缀和+二分

【2302. 统计得分小于 K 的子数组数目】前缀和+二分

作者:互联网

class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.countSubarrays(new int[]{
                2,1,4,3,5
        },10);
    }
    public long countSubarrays(int[] nums, long k) {
        int n = nums.length;
        long[] sum = new long[n+2];
        for (int i = 0; i < n; i++) {
            if (i == 0) {
                sum[1]= nums[0];
            }else{
                sum[i+1]=sum[i]+nums[i];
            }
        }
        sum[n+1] = sum[n];
        //
        long ans = 0;
        for (int i = 1; i <=n; i++) {
            int low = i - 1;
            int high = n + 1;

            while( low < high){
                int mid = (low + high)/2;
                if(check(nums,i,mid,k,sum)){
                    high = mid;
                }else{
                    low = mid + 1;
                }
            }
            if( high >=i){
                ans += (high -i);
            }

        }
        return ans;
    }

    public boolean check(int[] nums,int i,int j,long k,long[] sum){
        long x = (sum[j] - sum[i]+nums[i-1])*(j-i+1);
        return x>=k;
    }
}

 

标签:二分,前缀,nums,int,sum,2302,long,ans,new
来源: https://www.cnblogs.com/fishcanfly/p/16386819.html