连续子数组的最大和
2014-07-09 12:44
162 查看
题目:输入一个整型数组,数组里有正数也有负数。数组中一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。
bool InvalidInput = false; int GreatestSumOfSubarrays(int Numbers[], int nLength) { if (Numbers == NULL || nLength <= 0) { InvalidInput = true; return 0; } InvalidInput = false; int CurrentSum = 0; int GreatestSum = 0x80000000; for (int i = 0; i < nLength; i++) { if (CurrentSum < 0) CurrentSum = Numbers[i]; else CurrentSum += Numbers[i]; if (CurrentSum>GreatestSum) { GreatestSum = CurrentSum; } } return GreatestSum; } void test() { int testnums[] = {1,-2,3,10,-4,7,2,-5}; int result=GreatestSumOfSubarrays(testnums,sizeof(testnums)/sizeof(int)); printf("\t result is %d\n\n",result); } int _tmain(int argc, _TCHAR* argv[]) { test(); return 0; }
相关文章推荐