Sum of a sublist

Given a list of numbers L, implement a method sum(i, j) which returns the sum from the sublist L[i:j] (including i, excluding j).

For example, given L = [1, 2, 3, 4, 5]sum(1, 3) should return sum([2, 3]), which is 5.

You can assume that you can do some pre-processing. sum() should be optimized over the pre-processing step.

Example:

Input:  values = [1, 2, 3, 4, 5], i = 1, j = 3
Output: 5

Approach

C++

#include <bits/stdc++.h>
using namespace std;

vector<intsumArray;
void preprocessing(vector<int&values)
{

    for (int i = 1i < values.size(); i++)
    {
        sumArray[i] = sumArray[i - 1] + values[i];
    }
}
int sum(int iint j)
{
    return sumArray[j - 1] - sumArray[i - 1];
}

int main()
{
    vector<intvalues = {12345};

    int i = 1j = 3;
    sumArray.resize(values.size());
    preprocessing(values);

    cout << sum(ij);
    return 0;
}


No comments:

Post a Comment