Skip to content

Instantly share code, notes, and snippets.

@goyalankit
Created October 11, 2013 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goyalankit/6929844 to your computer and use it in GitHub Desktop.
Save goyalankit/6929844 to your computer and use it in GitHub Desktop.
Maximum Sum Problem
#include<iostream>
#include<algorithm>
using namespace std;
int main(int argc, char **argv){
int list[9] = {10, -1, 5, 6, 20, -50, 100, -100, 4};
int current_maximum = 0, previous_maximum=0;
bool evaluating = false;
for (int i = 0; i < 9 ;i++) {
if(current_maximum == 0 && list[i] < 0 && previous_maximum == 0){
continue;
}
if(list[i] < 0 && evaluating == false){
previous_maximum = current_maximum;
current_maximum = 0;
evaluating = true;
}
current_maximum += list[i];
if(evaluating ==true and current_maximum > 0){
current_maximum += previous_maximum;
evaluating = false;
}
}
cout << "maximum sum is " << max(current_maximum, previous_maximum) << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment