top of page

Daily Coding Problem #31

Writer's picture: Mischievous_FaceMischievous_Face

// 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.


#include <iostream>

#include <vector>


using namespace std;


int sum(vector<int> arr, int i, int j)

{

int total = 0;

for (;i < j; ++i)

total += arr[i];


return total;

}


int main()

{

// This problem is asking a very simple problem,

// the challenging part is optimizing it using pre-computing.

// I dont think the question includes enough info to answer properly,

// but if you want to make it more challenging, you would need to recursively

// go through all possible combinations and store them in a vector.

// Then you simply return the index from the matrix(i,j) of the pre-computed values

vector<int> arr = { 1 , 2, 3, 4, 5, 6 };

int i = 0;

int j = 6;

int result = sum(arr, i, j);


cout << "Sum from " << i << " to " << j << " is: " << result << endl;


return 0;

}






228 views0 comments

Recent Posts

See All

Comments


© 2020 Josh Painter

bottom of page