Drill

ProblemsC++ › reporting

Running balance down a statement

easyreportingArraysPrefix sumsC++

An account statement shows the balance after every movement, not just the final figure.

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.

Solve it in Python →

Where you start

std::vector<int> runningTotal(std::vector<int> amounts) {
    
}

Worked examples

CallResult
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;
}

The same problem in another language

More reporting problems in C++