做过的,就说下思路。
用Sum记录A[0...N-1]中 以第i个元素结尾的子数组中的最大和,
若以第i-1个元素结尾的子数组小于0,那么以第i个元素结尾的子数组中的最大和就是 A[i]本身 否则是A[i] + Sum(i-1的)
总结起来就是 Sum = (Sum > 0) ? A[i] + Sum : A[i];
再记录下所有出现过的Sum中最大的值就可以了。
#include <stdio.h> int getMaxSubArraySum(int * a, int alen) { int maxSum = a[0]; int Sum = a[0]; for(int i = 1; i < alen; i++) { Sum = (Sum > 0) ? Sum + a[i] : a[i]; maxSum = (Sum > maxSum) ? Sum : maxSum; } return maxSum; } int main() { int a[7] = {-2,5,3,-6,4,-8,6}; int b[6] = {1,-2,3,5,-3,2}; int c[6] = {0,-2,3,5,-1,2}; int d[5] = {-9,-2,-3,-5,-3}; int max = getMaxSubArraySum(d, 5); return 0; }