DEV Community

Cover image for Cumulative Sum
MICHAEL-MAURICE
MICHAEL-MAURICE

Posted on

2 2

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post