Simplest-Intuitive-Smallest O(n) C++ Code


#1

vector Solution::maxset(vector &a) {
int n = a.size();
vector v, ans;
long long sum = 0, max_sum = -1;

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){
			ans = v;
			max_sum = sum;
		}
		sum = 0;
		v.clear();
	}
}
return ans;

}