CODE with EXPLAINED EXAMPLE ! C++ | O(n)


#1

int Solution::solve(vector &A, int B) {
int n=A.size();
vector lefts(n+1,0);
lefts[0]=0; for(int i=1;i<=n;i++) lefts[i]=lefts[i-1]+A[i-1]; //prefix sum array

// for(int i:lefts) cout<<i<<" | ";
int cnt=0;
for(int i=1,j=1;i<=n;i++){
    int t=0;
    while(j<=n && lefts[j]<B+lefts[i-1]) {
        j++; 
    }
    
    // cout<<" for A[i]= "<<A[i-1]<<" cnt= "<<cnt<<"\t";
    if(j>=i)cnt+=(j-i); //adding the j-i subarrays to the answer
}
return cnt;

}