题目:https://cn.vjudge.net/contest/178832#problem/E
和最小子段和不一样,这道题可以尾首相连,就是在一个圈里找到最大子段和。
思路:可以找到最小子段和,用all-最小子段和,就是有首尾相连的最大字段,然后再和没有首尾相连的最大字段比较,最大者就是答案。
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
#define maxn 50000+5
int a[maxn];
long long dp[maxn],fdp[maxn];
int main()
{
int n,i,j;
while (~scanf("%d", &n))
{
fdp[0]=dp[0] = 0;
long long ans = 0,all=0;
for (i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
all += a[i];
fdp[i]=dp[i] = a[i];//存储最小子段和
dp[i] = max(dp[i], dp[i - 1] + a[i]);
fdp[i] = min(fdp[i], fdp[i - 1] + a[i]);
}
long long maxsum = 0, minsum = 0;
for (i = 1; i <= n; i++)
maxsum = max(dp[i], maxsum);
for (i = 1; i <= n; i++)
minsum = min(fdp[i], minsum);
ans = max(maxsum, all - minsum);
printf("%lld\n", ans);
}
return 0;
}