当前面计算的和是负数时,就没必要再用前面的结果了,curSum就等于当前数字,另外一个比较关键的问题是maxSum初值为最大的负数,只有这样才能保证一个序列最大值为负数时的结果正确性
1 bool g_InvalidInput = false; 2 3 int FindGreatestSumOfSubArray(int *pData, int nLength) 4 { 5 if((pData == NULL) || (nLength <= 0)) 6 { 7 g_InvalidInput = true; 8 return 0; 9 } 10 11 g_InvalidInput = false; 12 13 int nCurSum = 0; 14 int nGreatestSum = 0x80000000; 15 for(int i = 0; i < nLength; ++i) 16 { 17 if(nCurSum <= 0) 18 nCurSum = pData[i]; 19 else 20 nCurSum += pData[i]; 21 22 if(nCurSum > nGreatestSum) 23 nGreatestSum = nCurSum; 24 } 25 26 return nGreatestSum; 27 }