数组小练习
输入一个整形数组,数组里有正数也有负数,数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。 求所有子数组的和的最大值。要求时间复杂度为O(n)。
这道题只要一次遍历就可以求出最大的子数组和,而且是很简单的就解决了,具体想法是这样,不断的累加每个数组元素,并用一个变量保存当前的最大值,累加的过程一直和该变量进行比对,如果大于最大值,就把当前的最大值保存下来,反复如此就可以求出最大值。
int MaxSum(int* a, int n) { int nSum = 0; int nValue=0; for(int i = 0; i < n; i++) { if (nValue <= 0) nValue = a[i]; else nValue += a[i]; if(nSum < nValue) nSum = nValue; } return nSum; } int _tmain(int argc, _TCHAR* argv[]) { int anAry[] = {-2, 10,12, -20, 33}; //int nMaxValue = MaxSubArraySum(anAry, sizeof(anAry)/sizeof(int)); int nMaxValue = MaxSum(anAry, sizeof(anAry)/sizeof(int)); cout << "最大的子数组和为:" << nMaxValue << endl; return 0; }
转载于:https://blog.csdn.net/yuucyf/article/details/6342421#