the time complexity is O(n).
/* modified by quanspace 2013-01-30
* 实现最大子段和问题的线性级的算法 a linear time algorithm from Jay Kadane
* 最大子段和 maxsum 要么是空,取特定值0, 要么是 a[i]..a[j] 0<= i<= j<=n .
* a simple exeample of dynamic programming
* */
# include <iostream>
using namespace std;
struct max_subarr{
int ix_start;
int ix_end;
int maxsum;
};
int main(){
int a[16] = {13, -3, 20, -25, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7};
max_subarr ans;
ans.ix_start = 0, ans.ix_end = 0;
ans.maxsum = a[0];
int maxsum_temp = a[0];
for(int i = 1; i<16; ++i){
maxsum_temp += a[i];
if(maxsum_temp<a[i]){
maxsum_temp = a[i];
ans.ix_start = i;
}
if(maxsum_temp>ans.maxsum){
ans.maxsum = maxsum_temp;
ans.ix_end = i;
}
}
cout<<"The array is : ";
for(i = 0; i<16; ++i)
cout<<a[i]<<" ";
cout<<endl;
cout<<"The maxmum subarray is ";
for(i = ans.ix_start; i<= ans.ix_end; ++i)
cout<<a[i]<<" ";
cout<<endl;
cout<<"the maxsum is : "<<ans.maxsum<<endl;
return 0;
}
