Best Intuitive O(n) C++ Solution


#1

vector Solution::maxset(vector &A) {
vector v, ans;
long long sum=0, max_sum=-1;
int n=A.size();
for(int i=0; i<n; i++)
{
if(A[i]>=0)
{
v.push_back(A[i]);
sum+=A[i];
}
if(A[i]<0 || i==n-1)
{
if(sum>max_sum)
{
max_sum=sum;
ans=v;
}
sum=0;
v.clear();
}
}
return ans;
}