求解最大子序列和
【问题描述】
给定一个有n个整数的序列,要求求出其中最大子序列的和
【问题求解】
如果扫描遇到负数,当前子序列和 thisSum 将会减小,若 thisSum 为负数,表明前面已经扫描的那个子序列可以抛弃了,重新开始下一个子序列的分析,并置thisSum为0。若这个子序列和thisSum不断增加,那么最大子序列和maxSum也不断增加。
【代码】
//求解最大子序列和
//给定一个有n个整数的序列,要求求出其中最大子序列的和
#include<iostream>
using namespace std;
int maxSubSum(int a[], int n)
{
int maxSum = 0, thisSum = 0;
for (int i = 0; i < n; i++)
{
thisSum += a[i];
if (thisSum < 0)
thisSum = 0;
if (maxSum < thisSum)
maxSum = thisSum;
}
return maxSum;
}
int main()
{
int a[105], n;
cout << "请输入序列中数字的个数:";
cin >> n;
cout << "请依次输入数字:";
for (int i = 0; i < n; i++)
cin >> a[i];
cout << "最大子序列和为:" << maxSubSum(a, n) << endl;
system("pause");
return 0;
}
【算法分析】
显然该算法中仅扫描a一次,其算法的时间复杂度为O(n)。