I don’t understand how “Sum of array = cs[j]-cs[i-1]”
formula is formed
Cumulative Sum(cs)
Just dry run and check.
Consider an array:
2 4 5 6 8
Now cumulative sum array:
2 2+4 2+4+5…
which is 2 6 11 17 25
Now to find the sum of any subarray:
say for subarray starting from 2nd index to 4th index:
Subarray sum is cumsum[4]-cumsum[2-1]=25-6=19 (according to formula)
Subarray sum from 2nd index to 4th index: 5+6+8=19 which is same as the formula.
It is simple, just apply your logic and check.
Yes i get that but i don’t understand how this formula is formed.
P.S I know this a stupid question but i hope you will help to solve my query
Formula is derived simply by logic.
Let the cumulative sum array be:
2 6 11 17 25 This is the array which contains sum of all array elements upto 0th index at 0th pos, sum of all array elements upto 1st index at 1st position and so on…
Clearly if you want the sum of subarray starting from 1st index till the last index, you just need to subtract the cumulative sum at 0th position and you get the desired result.
Using this approach we get the formula “Sum of array = cs[j]-cs[i-1]”
If you still face any problem, please refer the lecture video again and you will understand.
Hope this helps
Got it . Thanks for helping me out
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.