版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bmicnj/article/details/68552938
sum[1], -sum[2],+sum[3],……和-sum[1],+sum[2],-sum[3]……两次最大字段和的最大值
代码:
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define MAXN 100010
using namespace std;
#define LL __int64
LL sum[MAXN],f[MAXN],a[MAXN];
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%I64d",&a[i]);
if(i>1)
sum[i-1]=abs(a[i]-a[i-1]);
}
int n1=n-1;
for(int i=2;i<=n;i+=2)
sum[i]=-sum[i];
f[0]=0;
f[1]=sum[1];
LL maxn=0;
for(int i=1;i<=n1;i++)
{
f[i]=max(sum[i],f[i-1]+sum[i]);
if(maxn<f[i])
maxn=f[i];
}
for(int i=1;i<=n1;i++)
sum[i]=-sum[i];
f[1]=sum[1];
for(int i=1;i<=n1;i++)
{
f[i]=max(sum[i],f[i-1]+sum[i]);
if(maxn<f[i])
maxn=f[i];
}
printf("%I64d\n",maxn);
return 0;
}