Running balance down a statement
An account statement shows the balance after every movement, not just the final figure.
- The result is the same length as the input.
- Each entry is the sum of everything up to and including that position.
runningTotal(amounts: list<int>) → list<int>
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
std::vector<int> runningTotal(std::vector<int> amounts) {
}
Worked examples
| Call | Result |
|---|---|
runningTotal(std::vector<int>{1, 2, 3}) | std::vector<int>{1, 3, 6} |
runningTotal(std::vector<int>{5, -5, 5}) | std::vector<int>{5, 0, 5} |
runningTotal(std::vector<int>{7}) | std::vector<int>{7} |
runningTotal(std::vector<int>{}) | std::vector<int>{} |
Hint
Carry one accumulator down the list and push it after each step.
Reference solution in C++
std::vector<int> runningTotal(std::vector<int> amounts) {
int sum = 0;
std::vector<int> result;
for (int a : amounts) { sum += a; result.push_back(sum); }
return result;
}