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.
rangeTotals(series: list<int>, starts: list<int>, ends: 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> rangeTotals(List<Integer> series, List<Integer> starts, List<Integer> ends) {
}
Worked examples
| Call | Result |
|---|---|
rangeTotals(Main.<Integer>ls(1, 2, 3, 4, 5), Main.<Integer>ls(0, 1, 0), Main.<Integer>ls(2, 3, 4)) | Main.<Integer>ls(6, 9, 15) |
rangeTotals(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(1), Main.<Integer>ls(1)) | Main.<Integer>ls(2) |
rangeTotals(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(2), Main.<Integer>ls(1)) | Main.<Integer>ls(0) |
rangeTotals(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(0), Main.<Integer>ls(99)) | Main.<Integer>ls(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 Java
List<Integer> rangeTotals(List<Integer> series, List<Integer> starts, List<Integer> ends) {
List<Integer> running = new ArrayList<>();
running.add(0);
for (int value : series) running.add(running.get(running.size() - 1) + value);
List<Integer> out = new ArrayList<>();
for (int i = 0; i < starts.size(); i++) {
int from = starts.get(i), to = ends.get(i);
if (from < 0 || to >= series.size() || from > to) out.add(0);
else out.add(running.get(to + 1) - running.get(from));
}
return out;
}