Counting Subarrays!

 https://www.interviewbit.com/old/problems/counting-subarrays/

 

int Solution::solve(vector<int> &A, int B) {
int i=0, j=0,count=0;
for (i=0; i<A.size(); i++){
    int sum=0;
    for (j=i; j>=0; j--){
        sum+=A[j];
        if(sum<B) count++;
        else break;
    }
}
return count;


int Solution::solve(vector<int> &A, int B) {
 int sum=0;
 int ans=0;
 int st=0;
 int end=0;
while(end<A.size())
{
sum=sum+A[end];
if(sum<B)
{
end++;
ans=ans+(end-st);
}
else
{
while(sum>=B)
{
sum=sum-A[st];
st++;
}
end++;
ans=ans+(end-st);
}
}
return ans;
}

Comments

Popular posts from this blog

Perfect Peak of Array

Is Rectangle?

Sort array with squares!