标签:
输入一个整型数组,数组里有正数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。例如输入的数组为{1,-2,3,10,-4,7,2,-5},和最大的子数组为{3,10,-4,7,2},因此输出为该子数组的和18.
剑指Offer(纪念版)P171
bool g_InvalidInput = false; int FindGreatestSumOfSubArray(int *pData, int nLength) { if((pData == NULL) || (nLength <= 0)) { g_InvalidInput = true; return 0; } g_InvalidInput = false; int nCurSum = 0; int nGreatestSum = 0x80000000; for(int i = 0; i < nLength; ++i) { if(nCurSum <= 0) nCurSum = pData[i]; else nCurSum += pData[i]; if(nCurSum > nGreatestSum) nGreatestSum = nCurSum; } return nGreatestSum; }
标签:
原文地址:http://www.cnblogs.com/xwz0528/p/4864307.html