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 l and r for the given array a.
Input
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.
Output
Print the only integer — the maximum value of f.
Examples
Input
5
1 4 2 3 1
Output
3
Input
4
1 5 4 7
Output
6
Note
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.
题目大意:
给出一个由n个数构成的序列,然后给出方程
求最大的f。
题目分析:
这道看上去很唬人(我当时就被唬住了),但其实并不难。
给出的方程可以转化为:定义一段序列b,b[i]=|a[i]-a[i+1]|*(-1)(i-1)(l<=i<r),即a中相邻两数差的绝对值乘上(-1)i-1.求这个序列b的字段和。这样,这道题目就转换为了一道求最大字段和的问题。我们可以将i的范围扩展到1一n-1,然后求出b的最大字段和。
因为f中l和r的位置不确定,因此我们要考虑两种情况:
- l的位置为奇数,此时b为+ - + - + - +…
- l的位置为偶数,此时b为- + - + - + -…
所以,我们分别求出这两种情况的最大子段和的最大值即可。
最大子段和求法参考Maximum sum
代码如下:
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <queue>
#include <algorithm>
#include <iomanip>
#define LL long long
using namespace std;
const int N=1e5+5;
LL a[N],b[N],c[N];
int main()
{
int n;
scanf("%d",&n); //因为数据量较大,输入要用scanf
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
for(int i=1;i<n;i++)
{ //分别计算两种情况的序列
if(i%2)
{
b[i]=abs(a[i]-a[i+1]);
c[i]=-b[i];
}
else
{
c[i]=abs(a[i]-a[i+1]);
b[i]=-c[i];
}
}
LL ans=0,sum=0; //答案有可能爆int
for(int i=1;i<n;i++) //计算两种情况的最大字段和
{
sum+=b[i];
if(sum<0) sum=0;
ans=max(ans,sum);
}
sum=0;
for(int i=1;i<n;i++)
{
sum+=c[i];
if(sum<0) sum=0;
ans=max(ans,sum);
}
printf("%lld\n",ans);
return 0;
}