The function can look as it is shown in the demonstrative program
#include <iostream>
#include <algorithm>
#include <vector>
long long int solution( const std::vector<int> &v )
{
long long int max_sum = 0;
for ( auto it = v.begin();
( it = std::find_if( it, v.end(), []( int x ) { return !( x < 0 ); } ) ) != v.end();
)
{
long long int sum = 0;
while ( it != v.end() && !( *it < 0 ) ) sum += *it++;
if ( max_sum < sum ) max_sum = sum;
}
return max_sum;
}
int main()
{
std::vector<int> v = { 1, 2, -3, 4, 5, -6 };
std::cout << solution( v ) << std::endl;
return 0;
}
Its output is
9
You can rewrite the function using indices instead of iterators.
As for your function then it is incorrect at least relative to this condition
if (max_ending_here < 0)
max_ending_here = 0;
because instead of checking the current element whether it is less than zero the condition checks the current sum of elements.
1
solved A Codility test that needs to be solved