int main() { int a[] = { -2, 11, -4, 13, -5, -2 }; for (int i = 0; i<6; i++) { printf("%d ", a[i]); } printf("\n"); printf("数组a的最大连续子段和为:%d\n", MaxSum(6, a)); return 0; }
int MaxSum(int *a, int begin, int end) { if (begin > end)return 0; if (begin == end)return (a[begin]>0)?a[begin]:0; int m = (begin + end) / 2; int leftsum = 0,lsum=0; for (int i = m; i >= begin; --i) { lsum += a[i]; leftsum = (lsum > leftsum) ? lsum : leftsum; } int rightsum = 0, rsum = 0; for (int i = m + 1; i <= end;++i) { rsum += a[i]; rightsum = (rsum > rightsum) ? rsum : rightsum; } return max(leftsum + rightsum, MaxSum(a, begin, m), MaxSum(a, m+1, end)); }
int main(int argc, char const *argv[]) { printf("%d\n",MaxSum(15) ); return 0; }
int main() { int A[6]={0,-2,3,5,-1,2}; printf("%d\n",MaxSum(A,6)); return 0; }