Suppose that I have an array consisting of n elements.
1 2 3 4 5 6 ... n
I need to find a way to extract the sums of consecutive elements in this array using C++.
Like this:
1, 2, 3,...n, 1+2, 2+3, 3+4,...(n-1)+n, 1+2+3, 2+3+4,...(n-2)+(n-1)+n,...1+2+3...n
So far I figured out I need to iterate through this array by summing certain number of elements on each run. I am not sure if it is possible to implement the algorithm I explained above. There might be a better solution but this is the best I could come up with.
Let’s inspect case with 4 elements:
As you can see every part for N sum array is of size lower from original array by (N-1). So you need target array of size: N + (N-1) + (N-2) + … 1 – which is N*(1+N)/2
See test on ideone