Something happened in Uzhlyandia again... There are riots on the streets... Famous Uzhlyandian superheroes Shean the Sheep and Stas the Giraffe were called in order to save the situation. Upon the arriving, they found that citizens are worried about maximum values of the Main Uzhlyandian Function f, which is defined as follows:
In the above formula, 1 ≤ l < r ≤ n must hold, where n is the size of the Main Uzhlyandian Array a, and |x| means absolute value of x. But the heroes skipped their math lessons in school, so they asked you for help. Help them calculate the maximum value of f among all possible values of land r for the given array a.
The first line contains single integer n (2 ≤ n ≤ 105) — the size of the array a.
The second line contains n integers a1, a2, ..., an (-109 ≤ ai ≤ 109) — the array elements.
Print the only integer — the maximum value of f.
5
1 4 2 3 1
3
4
1 5 4 7
6
In the first sample case, the optimal value of f is reached on intervals [1, 2] and [2, 5].
In the second case maximal value of f is reachable only on the whole array.
类似于最大循环字段和,不难发现最大子段和出现的情况分为两种:
1 +-+-+-...
2 -+-+-+...(此时一定不是从第一个数开始的所以将第一个数也置负即可)
所以只要更改+-求两次最大子段取最大值就ok
#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define inf 0x7fffffff
LL a[100005];
LL LLS(int n)
{
LL sumn=0,maxn=-inf,i;
//cout<<"ssss:"<<maxn<<endl;
for(i=1;i<=n;++i){
sumn+=a[i];
maxn=max(maxn,sumn);
if(sumn<0) sumn=0;
}
return maxn;
}
int main()
{
LL n,i,j;
while(cin>>n){
for(i=1;i<=n;++i){
scanf("%lld",&a[i]);
if(i==1) continue;
a[i-1]=abs(a[i-1]-a[i]);
}
//for(i=1;i<n;++i) cout<<a[i]<<" ";
for(i=2;i<=n;i+=2) a[i]=-a[i];
j=LLS(n-1);
for(i=1;i<=n-1;++i) a[i]=-a[i];
cout<<max(j,LLS(n-1))<<endl;
}
return 0;
}