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<int> sumArray;void preprocessing(vector<int> &values){for (int i = 1; i < values.size(); i++){sumArray[i] = sumArray[i - 1] + values[i];}}int sum(int i, int j){return sumArray[j - 1] - sumArray[i - 1];}int main(){vector<int> values = {1, 2, 3, 4, 5};int i = 1, j = 3;sumArray.resize(values.size());preprocessing(values);cout << sum(i, j);return 0;}
No comments:
Post a Comment