本次测试选用的杜晓松的代码,我本人的在25w个元素时已挂。int最大支持到万位...
//XiaoSong Du 2015/3/22 #include <iostream> #include <time.h> using namespace std; #define N 1000 void main() { int a[N],d = 0,d1 = 0; int maxd ,maxd1,end1 = 0,end2=0; srand((unsigned int)time(0)); for (int i = 0;i < N;i++) { a[i] = rand()%50 - 25; cout << a[i] << " "; } cout << endl; maxd = a[0]; for (int i = 0;i < N;i++) { d += a[i]; if (d > maxd) { maxd = d; end1 = i; } if(d < 0) { d = 0; } } maxd1 = a[N-1]; for (int i = N-1;i >= 0;i--) { d1 += a[i]; if (d1 > maxd1) { maxd1 = d1; end2 = i; } if(d1 < 0) { d1 = 0; } } cout << "子数组为:"; for (int i = end2;i <= end1;i++) cout << a[i] << " "; cout << endl; cout << "和为: " << maxd << endl; }
结果截图: