C++ | Counting Subarrays! | O(n) sliding window approach


#1
int Solution::solve(vector<int> &A, int B) {
    
    int i=0, j=0, len = A.size();
    if(not B) return (len*len+1)/2;
    int sum = 0, count = 0;

    while(j < len) {
        if(A[j]+sum < B)
            sum += A[j ++];
        else {
            count += (j-i);
            sum -= A[i ++];
        }
    }

    count += ((j-i)*(j-i+1))/2;
    return count;
}