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>
Go 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
func runningTotal(amounts []int) []int {
}
Worked examples
| Call | Result |
|---|---|
runningTotal([]int{1, 2, 3}) | []int{1, 3, 6} |
runningTotal([]int{5, -5, 5}) | []int{5, 0, 5} |
runningTotal([]int{7}) | []int{7} |
runningTotal([]int{}) | []int{} |
Hint
Carry one accumulator down the list and push it after each step.
Reference solution in Go
func runningTotal(amounts []int) []int {
sum := 0
result := []int{}
for _, a := range amounts {
sum += a
result = append(result, sum)
}
return result
}