子数组最大和
文章目录
//数组的最大子数组的和并返回
//动态规划分f(i)=pData[i] i=0 or f(i-1)<=0;
//f(i)=f(i-1)+pData[i] i!=0 and f(i-)>0;
#include <iostream>
using namespace std;
bool g_InvalidInput=false;//标记结果0到底是无效输入还是 最大和是0
int FindGreatestSumOfSubArray(int* pData,int nLength){
if(pData==NULL||nLength<=0){
g_InvalidInput=true;
return 0;
}
g_InvalidInput=false;
int nCurSum=0;
int nGreatestSum=0x80000000;
for(int i=0;i<nLength;i++){
if(nCurSum<=0)
nCurSum=pData[i];
else
nCurSum+=pData[i];
if(nCurSum>nGreatestSum)
nGreatestSum=nCurSum;
}
return nGreatestSum;
}
int main()
{
int a[]={1,-2,3,10,-4,7,2,-5};
cout<<FindGreatestSumOfSubArray(a,8);
return 0;
}