0

This is a snippet from this code to finding sums of all subarrays of a given array, but this doesn't work as intended as the problem seems to be lying with pre-incrementing value of i in the equation.

while(i<vec.size()-1){
  sum += -vec[i-2] + vec[++i] ;
  nums.emplace_back(sum);
}
return nums;

However, when i deploy this code which seems to be the same implementation as the previous one, the code runs correctly:

while(i<vec.size()-1){
  sum += -vec[i-2] + vec[i+1] ;
  nums.emplace_back(sum);
  i++;
}

Please Clarify!

I tried it on: (1,2,3,4,) Expected: 6,9,12 Output from 1st snippet: 6,8,10 //Incorrect Output from 2nd snippet: 6,9,12 //Correct

3
  • 1
    Share the data format of the arrays... and What language are you using? Commented Nov 26, 2023 at 7:22
  • Why does your expected output only have 3 values? An array of 4 elements has 10 subarrays ... And how would you get a sum of 12, when all elements in the array only sum up to 10? Commented Nov 26, 2023 at 14:08
  • The code is written in C++. The data format: vector<int> (if thats what you asked) And sorry the input array is: 1,2,3,4,5 and not 1,2,3,4, (mistake on my part, its my first question ever :_) ) Thanks for your response.. Commented Nov 26, 2023 at 18:16

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.