Answer a stack of range totals
A reporting screen asks for the total of many different day ranges over the same series, and asks a lot of them.
- Each query is a pair taken from the two lists by position: `starts[i]` to `ends[i]`.
- Both ends are inclusive.
- A query whose range falls outside the series, or runs backwards, totals 0.
- Return one total per query, in the order the queries came.
range_totals(series: list<int>, starts: list<int>, ends: list<int>) → list<int>
Where you start
def range_totals(series: list[int], starts: list[int], ends: list[int]) -> list[int]:
Worked examples
| Call | Result |
|---|---|
range_totals([1, 2, 3, 4, 5], [0, 1, 0], [2, 3, 4]) | [6, 9, 15] |
range_totals([1, 2, 3], [1], [1]) | [2] |
range_totals([1, 2, 3], [2], [1]) | [0] |
range_totals([1, 2, 3], [0], [99]) | [0] |
Hint
Build the running total once, up front. Then any range is one subtraction — the total up to the end, less the total before the start.
Reference solution in Python
def range_totals(series: list[int], starts: list[int], ends: list[int]) -> list[int]:
running = [0]
for value in series:
running.append(running[-1] + value)
out = []
for i in range(len(starts)):
from_i, to_i = starts[i], ends[i]
if from_i < 0 or to_i >= len(series) or from_i > to_i:
out.append(0)
else:
out.append(running[to_i + 1] - running[from_i])
return out