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>
Java 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
List<Integer> runningTotal(List<Integer> amounts) {
}
Worked examples
| Call | Result |
|---|---|
runningTotal(Main.<Integer>ls(1, 2, 3)) | Main.<Integer>ls(1, 3, 6) |
runningTotal(Main.<Integer>ls(5, -5, 5)) | Main.<Integer>ls(5, 0, 5) |
runningTotal(Main.<Integer>ls(7)) | Main.<Integer>ls(7) |
runningTotal(Main.<Integer>ls()) | Main.<Integer>ls() |
Hint
Carry one accumulator down the list and push it after each step.
Reference solution in Java
List<Integer> runningTotal(List<Integer> amounts) {
int sum = 0;
List<Integer> result = new ArrayList<>();
for (int a : amounts) { sum += a; result.add(sum); }
return result;
}