Create a variable for the the running sum and a variable for the output vector.
For each item in the input vector
if it's positive, add it to the running sum
otherwise add the running sum to the output vector and then reset the sum to zero.
That's it... almost....
Test it with v = {1 2 3 -4 -5 -6 7 8 -1}
Adjust the code so it works for this case.
Now test with v = { 1 2 3 -4 5 6}
Fix the code again.
Now test with v = {-1 -2 3 4 5 -6 7 8 9}
Fix the code again.
Rerun the tests to make sure you haven't broken anything.
int sum =0;
vector <int> vals;
int N = vals.size();
for (int i=0; i < n; i++)
{
while (vals[i] >0 )
{sum = sum + vals[i];
w.push_back(sum);
}
sum = 0;
i++;
}
#include <vector>
std::vector<int> sums_of_positive_subsequences( const std::vector<int>& seq )
{
std::vector<int> result ;
int sum = 0 ; // sum of current positive subsequence
for( std::size_t i = 0 ; i < seq.size() ; ++i )
{
if( seq[i] > 0 ) sum += seq[i] ; // positive
else /* seq[i] is non-positive (negative or zero) */ if( sum > 0 ) // if we have a sum
{
result.push_back(sum) ;
sum = 0 ;
}
}
if( sum > 0 ) /* if there is sum remaining at the end */ result.push_back(sum) ;
return result ;
}
OP: you edited your first post 15 minutes after JLBorges' reply, removing the actual statement of your problem and leaving just the code in, which is a very poor thing to do as the code without context is useless. Please reinstate it.
I don't know if anyone has saved your original post but as far as I can recall you wanted to include a positive number from the std::vector<int> for summing in case it was followed by at least one other positive number, otherwise the positive number would not be considered for summing. Based on my recollection/interpretation: