Cumulative (Prefix) Sum (Part 1)
in this article, we will talk about Cumulative sum but first, let me talk about one of the most
a 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(i)).
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?
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()
{
//zero based
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;
}
ONE BASED
Comments
Post a Comment