Drill

ProblemsC# › patterns

Answer a stack of range totals

mediumpatternsPrefix sumsArraysC#

A reporting screen asks for the total of many different day ranges over the same series, and asks a lot of them.

RangeTotals(series: list<int>, starts: list<int>, ends: 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.

Solve it in Python →

Where you start

public List<int> RangeTotals(List<int> series, List<int> starts, List<int> ends) {
    
}

Worked examples

CallResult
RangeTotals(new List<int> { 1, 2, 3, 4, 5 }, new List<int> { 0, 1, 0 }, new List<int> { 2, 3, 4 })new List<int> { 6, 9, 15 }
RangeTotals(new List<int> { 1, 2, 3 }, new List<int> { 1 }, new List<int> { 1 })new List<int> { 2 }
RangeTotals(new List<int> { 1, 2, 3 }, new List<int> { 2 }, new List<int> { 1 })new List<int> { 0 }
RangeTotals(new List<int> { 1, 2, 3 }, new List<int> { 0 }, new List<int> { 99 })new List<int> { 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 C#
public List<int> RangeTotals(List<int> series, List<int> starts, List<int> ends) {
    var running = new List<int> { 0 };
    foreach (var value in series) running.Add(running[running.Count - 1] + value);
    var outList = new List<int>();
    for (int i = 0; i < starts.Count; i++) {
        int from = starts[i], to = ends[i];
        if (from < 0 || to >= series.Count || from > to) outList.Add(0);
        else outList.Add(running[to + 1] - running[from]);
    }
    return outList;
}

The same problem in another language

More patterns problems in C#