题目:输入一个整形数组,数组里有正整数也有负数。数组中一个或连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求时间复杂度为O(n)。
#include "iostream"
using namespace std;
bool gdataValide =true;
int Getmaxsum(int* pData,int nLength)
{
int sum =0;
int max =0;
if (pData ==NULL)
{
gdataValide =false;
return -1;
}
for (int i=0;i<nLength;i++)
{
if (sum<0)
sum =pData[i];
else
sum+=pData[i];
if (sum>max)
{
max =sum;
}
}
return max;
}
void main()
{
int array[8] ={1,-2,3,10,-4,7,2,-5};
cout<<Getmaxsum(array,8)<<endl;
}