面试题27:连续子数组的最大和
注意:当函数输入无效时,返回为0,而子数组的和也有可能为0,为了区分,设置一个全局变量标记输入是否有效。
思路用下表说明:
代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
bool bInvalidInput = false;//用全局变量标记是否为无效输入
//求连续子数组的最大和
int FindGreatestSumOfSubArray(int nArr[], int nLength)
{
if (nArr == NULL || nLength <=0)
{
bInvalidInput = true;
return 0;
}
int nGreatestSum = 0x80000000;//记录连续子数组的最大和,初始值设置为很小的负数
int nCurrentSum = 0;
for (int i=0; i<nLength; i++)
{
if (nCurrentSum <= 0)
{
nCurrentSum = nArr[i];
}
else
{
nCurrentSum += nArr[i];
}
if (nCurrentSum > nGreatestSum)
{
nGreatestSum = nCurrentSum;
}
}
return nGreatestSum;
}
int _tmain(int argc, _TCHAR* argv[])
{
int nArr1[8] = {1, -2, 3, 10, -4, 7, 2, -5};
int nGreatestSumOfSubArray1 = FindGreatestSumOfSubArray(nArr1, 8);
if (!bInvalidInput)
{
cout << "连续子数组的最大和为:" << nGreatestSumOfSubArray1 << endl;
}
int nArr2[8] = {-1, -2, -3, -10, -4, -7, -2, -5};
int nGreatestSumOfSubArray2 = FindGreatestSumOfSubArray(nArr2, 8);
if (!bInvalidInput)
{
cout << "连续子数组的最大和为:" << nGreatestSumOfSubArray2 << endl;
}
return 0;
}
运行结果: