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
题意:给出一个n,表示数组a的元素个数,接下来n个数为a【i】,,问f最大值是什末。
思路:这个题跟以前做过的max sum 非常像,其实另开一个数组b,数组b中存的是a[ i ]- a[i+1],然后不管 l 和 r 是多少,第一个pow(-1,i-l)为正,第二个为负,得奇数为负,偶数为正,用一个数k记录一下正负即可,我们见假设从1开始,如果发现加的过程中sum值为负数,这种情况怎末加也不会最大。然后从第二个元素开始加,实时更新一下maxx的值最后输出来即可,代码如下:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define N 100010
using namespace std;
long long int a[N],b[N];
int main()
{
int n,i;
long long sum,maxx,k,v;
while(~scanf("%d",&n)&&n)
{
sum=maxx=k=0;
v=1;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(i=1;i<=n;i++)
scanf("%lld",&a[i]);
for(i=1;i<n;i++)
b[i]=abs(a[i]-a[i+1]);
for(i=v;i<n;i++)
{
if(k%2==0)
{
sum=sum+b[i]; //k是偶数相加
k++;
}
else
{
sum=sum-b[i];//k是奇数相减
k++;
}
if(sum>maxx)
maxx=sum; //更新maxx的值
if(sum<0) //如果sum小与0,舍弃这种情况
{
sum=0;
k=0;
i=v++;
}
}
printf("%lld\n",maxx);
}
return 0;
}