A shop records how much money it makes each day. Print the total made up to and including each day.
What to build
Read the n daily amounts and print n numbers: the first is the first amount, the second is the sum of the first two, and so on.
Requirements
- Use a prefix-sum array of
long long - Print the running totals on one line, separated by spaces
Input
The first line has n. The second line has n whole numbers (each from -10⁹ to 10⁹).
Output
n numbers: the sum of the first 1, 2, ..., n amounts.
Constraints
1 ≤ n ≤ 100,000. Totals can reach 10¹⁴, so use long long.
Example
Input:
5
3 1 4 1 5
Output:
3 4 8 9 14
Why it works
Each total is the one before it plus the new amount, which is exactly how a prefix-sum array is built. One pass, O(n).
Examples
5 3 1 4 1 5
3 4 8 9 14
3 -2 2 -2
-2 0 -2
Hints
Hint 1
Keep a variable total = 0 and add each number to it.
Hint 2
Print total after each addition.
Hint 3
Use long long: 10⁵ values of 10⁹ is 10¹⁴.
Solution
Show one correct solution (try it yourself first)
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
long long total = 0;
for (int i = 0; i < n; i++) {
long long x;
cin >> x;
total += x;
cout << total << " ";
}
cout << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step