7-2 Maximum Subsequence Sum (25分)

Sample Input:
10
-10 1 2 3 4 -5 -23 3 7 -21
Sample Output:
10 1 4
#include<iostream>
using namespace std;
#include<vector>
int main()
{
int n,thisSum=0,maxSum=-1;
vector<int>substr,allstr,maxstr;
cin>>n;
while(n--)
{
int num;
cin>>num;
allstr.push_back(num);
substr.push_back(num);
thisSum+=num;
if(maxSum<thisSum)
{
maxSum=thisSum;
maxstr=substr;
}
else if(thisSum<0)
{
thisSum=0;
substr.clear();
}
}
if(maxSum>=0)
cout<<maxSum<<" "<<maxstr[0]<<" "<<maxstr[maxstr.size()-1]<<endl;
else
cout<<0<<" "<<allstr[0]<<" "<<allstr[allstr.size()-1]<<endl;
}
该程序实现了求解数组中连续子序列的最大和问题,输入一个整数数组,输出最大子序列和及其起始和结束元素。例如,对于输入数组[-10, 1, 2, -3, 4, -5, 2, 3, -21],最大子序列和为9,对应的子序列是[4, -5, 2, 3],起始元素为4,结束元素为3。
5935

被折叠的 条评论
为什么被折叠?



