作业:求一个整数数组所有子数组的和的最大值
#include<iostream>
using namespace std;
bool Find(int *pData, unsigned int nLength, int &nGreatestSum)
{
if(pData == NULL || nLength == 0)
return false;
int nCurSum = nGreatestSum = 0;
for(unsigned int i = 0; i < nLength; i++)
{
nCurSum += pData[i];
if(nCurSum < 0)
nCurSum = 0;
if(nCurSum > nGreatestSum)
nGreatestSum = nCurSum;
}
if(nGreatestSum == 0)
{
nGreatestSum = pData[0];
for(unsigned int i = 1; i < nLength; i++)
{
if(pData[i] > nGreatestSum)
nGreatestSum = pData[i];
}
}
cout<<nGreatestSum<<endl;
return true;
}
int main()
{
int a[] = {1, 2, -3, 10, 4, -7, 2, -5};
int greatNum;
Find(a, sizeof(a) / sizeof(int), greatNum);
//
system("pause");
return 0;
}
结果: