最大连续子数组和(最大子段和)
问题: 给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n
例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。
源代码:
#include <iostream>
using namespace std;
int main()
{
int n;
int maxSum=0;
int nowSum=0;
cin>>n;
for(int i=1;i<=n;i++)
{
int num;
cin>>num;
nowSum+=num;
if(nowSum>maxSum)maxSum=nowSum;
if(nowSum<0)nowSum=0;
}
cout<<maxSum<<endl;
return 0;
}
标签:子段,int,nowSum,cin,num,实验,maxSum From: https://www.cnblogs.com/xuyuting/p/16862843.html