Cumulative sum of Subarray
Lesson 25 of 26 in Coddy's Arrays in C++ course.
A cumulative sum Array is an array of all the sums of an array till that index.
For example,
Arr={1,2,3,4}
for i=0 cumulative sum will be 1
for i=1 cumulative sum will be 1+2=3
for i=2 cumulative sum will be 1+2+3=6
for i=3 cumulative sum will be 1+2+3+4=10
So the cumulative array becomes {1,3,6,10}
One way of calculating it is by using two loops nested and calculating um and storing it in an array. As
int k=0;
while(k<n){
int sum=0;
for(int j=0;j<k+1;j++){
sum=sum+arr[j];
}
ans[k]=sum;
k++;
}The other and the most efficient way of calculating the cumulative array is by adding the current element to the previous sum.
Arr={1,2,3,4}
cumArr[] is cumulative array.
- cumArr[0]=1
- cumArr[1]=prev sum+Arr[1] = 1 + 2 = 3
- cumArr[2]=prev sum+Arr[2] = 3 + 3 = 6
- cumArr[3]=prev sum+Arr[1] = 6 + 4= 10
It can be executed as
int sum=0;
for(int i=0;i<n;i++){
sum=sum+arr[i];
ans[i]=sum;
}Brainteaser
What do you think will be the time complexity of both of these approaches ??
Try it yourself
This lesson doesn't include a code challenge.
All lessons in Arrays in C++
2Memory Analysis
Memory Allocation8Subarray
IntroductionSubsequencePrinting all SubarraysSubarray with given sumCumulative sum of SubarrayKadane's Algorithm