PAT (Advanced Level) 1007. Maximum Subsequence Sum (25)

时间:2023-01-12 12:47:14

简单DP。

注意:If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence.

#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<vector>
using namespace std; const int maxn=;
int n,a[maxn],sum,ans1,ans2;
int dp[maxn]; int main()
{
scanf("%d",&n);
for(int i=; i<=n; i++) scanf("%d",&a[i]);
dp[]=a[];
for(int i=; i<=n; i++) dp[i]=max(dp[i-]+a[i],a[i]);
int Max=-;
for(int i=; i<=n; i++) Max=max(Max,dp[i]);
if(Max<) printf("0 %d %d\n",a[],a[n]);
else
{
for(int i=; i<=n; i++)
{
if(dp[i]==Max)
{
ans2=a[i]; int sum=;
for(int j=i; j>=; j--)
{
sum=sum+a[j];
if(sum==Max) { ans1=a[j]; break; }
}
break;
}
}
printf("%d %d %d\n",Max,ans1,ans2);
}
return ;
}