Prefix sums are very handy when working with ranges in arrays. It’s possible to optimize the programs many times by making use of the prefix sum of an array instead of calculating the sum every time.
Imagine a problem where we need to answer many queries (millions) “What will be the sum of elements of the array a from the beginning to ?”. So, a naive approach would be to calculate the sum a + a + a + ... + a every time. As an example, if we have an array and queries:
Notice how the first part of the computation is always the same. Before calculating res2, we already know the result of a + a + a + a, which was exactly res1. Before calculating res4, we already know the result for a + a + a + a + a + a. We can definitely optimize these calculations and respond to queries instantly instead of running a for loop every time.
To do that, we can store a new array p of prefix sums, where the elements of p will represent the sum of elements in the initial array a up to that index. If we do that, the answer to each query will be just accessing an element from the prefix sum:
Notice the pattern - to calculate the next element in the prefix array p, we repeat all the actions in the previous one and then add one more element from a. Having that, we can use the previous calculations to avoid adding the same numbers over and over:
This can be calculated with a single for loop in linear time instead of having multiple loops that do the same computation over and over. After computing the prefix sum array p, we will be able to answer all the queries instantly - as p[i] holds the information about the sum a + a + a + ... + a[i]. So, for each query , the response will just be p.
Can you calculate the prefix sum array now?
The first line of the input contains a single integer n (1 ≤ n ≤ ). The second line of the input contains n space-separated integers representing the array a.
The program should output the prefix sum array of a.