DEV Community

Cover image for Cumulative Sum
MICHAEL-MAURICE
MICHAEL-MAURICE

Posted on

Cumulative Sum

in this article, I will talk about Cumulative sum but first, let me talk about one of the most common problem in computer science if we have an array and we wanna calculate the summation
of a specific range in this array, you will think of nested loops that sound good.
but this solution is (o(n)^2) can we get a better solution ??
Yes, we can do that by using (cumulative sum). ok, what is that exactly?

The cumulative sum is a technic we use to get the summation of a specific range in an array in(o(1)).
by generating a new array each element in that array contain the summation of elements before that

element.

ok, How we can write this code?

Image description

ZERO BASED

int range(int s,int e,vector<int>&v){
if(s==0)
    return v[e];
    return v[e]-v[s-1];
}
int main()
{

    vector<int>v={1,2,3,4,5,6};
    vector<int>s(v.size(),0);
    for(int i=0;i<v.size();i++){
        s[i]+=(i==0)?v[i]:v[i]+s[i-1];
    }
    cout<<range(2,4,s);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

ONE BASED

int range(int s,int e,vector<int>&v){
    return v[e]-v[s-1];
}
int main()
{//one based
    vector<int>v={0,1,2,3,4,5,6};
    vector<int>s(v.size(),0);
    for(int i=1;i<v.size();i++){
        s[i]+=v[i]+s[i-1];
    }
    cout<<range(2,4,s);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)