#include <iostream>
using namespace std;
long long getMaxSum( int a[], int low, int high )
{
long long max = -INT_MAX - 1;
long long sum = 0;
if( NULL == a || low > high )
{
cout << "getMaxSum func: err -1, NULL==a || low > high" << endl;
max = -1;
return max;
}
for( int i = low; i <= high; ++i )
{
sum += a[i];
if( sum > max )
{
max = sum;
}
if( sum < 0 )
{
sum = 0;
}
}
return max;
}
int main()
{
int ret = 0;
//int num = 0x80000001;
int a[] = { 1, -2, 3, 10, -4, 7, 2, -5 };
cout << getMaxSum( a, 0, 7 ) << endl;
return ret;
}
/*
应用动态规划思想:
f(i)表示以第i个数字结尾的子数组的最大和,即所求为:max[f(i)]
f(i) = pData[i] // i = 0或f(i-1)<=0
f(i) = f(i-1) + pData[i] // i != 0并且f(i-1)>0
f(i)相当于sum
max[f(i)]相当于max
*/
面试题31:连续子数组的最大和
最新推荐文章于 2021-05-20 12:19:18 发布