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.
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.
题目大意:
事情发生在Uzhlyandia…街上有暴动…著名的uzhlyandian超级商羊和STA长颈鹿被任命拯救世界。在到达后,他们发现,市民担心的主要uzhlyandian函数最大值 f,被定义为:
在上面的公式中,保证1 ≤ l < r ≤ n 其中 n 表示 Uzhlyandian 数列 a 的大小 , |x| 表示 x的绝对值。但是英雄们在学校里跳过数学课,所以他们向你寻求帮助。帮助他们计算 f 数组中的最大值, l 和 r 任选,通过给定的数组 a.
题目分析: 本来想的是开二维数组,很明显太大,然后想试试用数组的方法,就开1000*1000的,然后还不错,在第十个数据上re的,意料之中。然后就回头继续想方法,突然想到,这题很像那个最大子序列之和的,,,然后当时写完之后,居然一遍就过了样例,很是兴奋呀,后来提交wr在了第5个数据上,回头看发现是因为这个题目的每一项的正负是根据首项选谁确定的,所以是会发生改变的,然后把这个改掉之后就ac 了,少年还是需要继续加油。
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
const int maxn = 100005;
long long a[maxn];
long long b[maxn];
int main(){
int n;
while((scanf("%d",&n))!=EOF){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=1;i<n;i++)
b[i] = abs(a[i]-a[i+1]);
long long l=0,mx=0;
int flag=0;
int k=1;
for(int i=k;i<n;i++){
if(flag %2 == 0 ){
l+=b[i];
flag++;
}
else {
l-=b[i];
flag++;
}
if(l>mx){
mx=l;
}
if(l<0){
l=0; flag=0;
i--;
i=k++;
}
}
cout<<mx<<endl;
}
return 0;
}