【练习】求子数组的最大和
/************************************************************************/ /* 求子数组的最大和 题目: 输入一个整形数组,数组里有正数也有负数。 数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。 求所有子数组的和的最大值。要求时间复杂度为O(n)。 例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2, 因此输出为该子数组的和18。 */ /************************************************************************/ #include <iostream> using namespace std; #define LENGTH 8 void MaxSubSum(int* array) { int maxSum=0,currentSum=0; int BeginIndex=0,EndIndex=0;//保存数组最大子数组和的起止下标 for(int i=0;i<LENGTH;i++) { cout<<array[i]<<" "; currentSum+=array[i]; if (currentSum>maxSum) { maxSum=currentSum; EndIndex=i; } else if(currentSum<0)//说明这之前的数组元素之和小于0,因此去掉 { currentSum=0; BeginIndex=i+1; } } cout<<endl<<"The max subArray is: "<<endl; for (int i=BeginIndex;i<=EndIndex;i++) { cout<<array[i]<<" "; } cout<<endl<<"Max sum is :"<<maxSum<<endl; } int main() { int array[]={1, -2, 3, 10, -4, 7, 2, -5}; MaxSubSum(array); return 0; }