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
public List<int> RunningTotal(List<int> amounts) {
}
Worked examples
| Call | Result |
|---|---|
RunningTotal(new List<int> { 1, 2, 3 }) | new List<int> { 1, 3, 6 } |
RunningTotal(new List<int> { 5, -5, 5 }) | new List<int> { 5, 0, 5 } |
RunningTotal(new List<int> { 7 }) | new List<int> { 7 } |
RunningTotal(new List<int> { }) | new List<int> { } |
Hint
Carry one accumulator down the list and push it after each step.
Reference solution in C#
public List<int> RunningTotal(List<int> amounts) {
int sum = 0;
var result = new List<int>();
foreach (var a in amounts) { sum += a; result.Add(sum); }
return result;
}