struct maxInfo{ int start; int end; int max;};bool maxValue(int a[], int n, maxInfo& mi ){ if( n < 0 ) { return false;} mi.start = mi.end = 0; mi.max = a[0]; int i; int curValue = mi.max; for( i = 1; i < n ; i ++) { if(curValue + a[i] > mi.max) { if(curValue < 0 ) { mi.start = mi.end = i; mi.max = a[i]; curValue = a[i]; } else { mi.end = i; mi.max += a[i]; curValue +=a[i]; } } else { curValue += a[i]; } } return true;}
The algorithm is simple as follows:
The test code is as follows:
#include <iostream>#include <vector>#include <iterator>#include <istream>using namespace std;struct maxInfo{ int start; int end; int max;};void maxValue(vector<int> a, maxInfo &mi){ mi.start = mi.end = 0; mi.max = a[0]; int i; int curValue = mi.max; int n = a.size(); for( i = 1; i < n ; i ++) { if(curValue + a[i] > mi.max) { if(curValue < 0 ) { mi.start = mi.end = i; mi.max = a[i]; curValue = a[i]; } else { mi.end = i; mi.max += a[i]; curValue +=a[i]; } } else { curValue += a[i]; } }}int main(){ maxInfo mi; cout << "Input the datas : " ; istream_iterator<int> begin(cin), end; vector<int> vc(begin, end); maxValue(vc, mi); cout << "[ " << mi.start << ", " << mi.end << " ]" << endl; cout << "Max value is: " << mi.max <<endl; cout << "Sub array is : " <<endl; copy(vc.begin() + mi.start, vc.begin() + mi.end + 1, ostream_iterator<int> (cout, " ")); return 0;}