1. 程式人生 > >cf789c

cf789c

主要是線性時間內求最大連續和

#include<bits/stdc++.h>
using namespace std;
#define maxn 200005
#define ll long long

int n,a[maxn];
ll ans;

ll solve(){
    ll Max=-99999999,Min=0,sum[maxn];
    sum[0]=0;
    for(int i=1;i<n;i++){
        sum[i]=sum[i-1]+a[i];
        Min=min(Min,sum[i]);
        Max=max(Max,sum[i]-Min);
    }
    
return Max; } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int i=1;i<=n-1;i++) a[i]=abs(a[i+1]-a[i]); for(int i=1;i<=n-1;i++) if(i%2==0) a[i]/=-1; ans=-99999999; ans=max(ans,solve()); for(int i=1;i<=n-1;i++) a[i]*=-1; ans
=max(ans,solve()); printf("%lld",ans); }