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

std::vector<int> rangeTotals(std::vector<int> series, std::vector<int> starts, std::vector<int> ends) {
    
}

Worked examples

CallResult
rangeTotals(std::vector<int>{1, 2, 3, 4, 5}, std::vector<int>{0, 1, 0}, std::vector<int>{2, 3, 4})std::vector<int>{6, 9, 15}
rangeTotals(std::vector<int>{1, 2, 3}, std::vector<int>{1}, std::vector<int>{1})std::vector<int>{2}
rangeTotals(std::vector<int>{1, 2, 3}, std::vector<int>{2}, std::vector<int>{1})std::vector<int>{0}
rangeTotals(std::vector<int>{1, 2, 3}, std::vector<int>{0}, std::vector<int>{99})std::vector<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++
std::vector<int> rangeTotals(std::vector<int> series, std::vector<int> starts, std::vector<int> ends) {
    std::vector<int> running{0};
    for (int value : series) running.push_back(running.back() + value);
    std::vector<int> out;
    for (size_t i = 0; i < starts.size(); i++) {
        int from = starts[i], to = ends[i];
        if (from < 0 || to >= static_cast<int>(series.size()) || from > to) out.push_back(0);
        else out.push_back(running[to + 1] - running[from]);
    }
    return out;
}

The same problem in another language

More patterns problems in C++