题干:
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 (2 ≤ n ≤ 105) — 表示数组 a的大小。
第二行包含 n 个整数 a1, a2, ..., an (-109 ≤ ai ≤ 109) — 表示数组。
让你找一段连续区间[l,r],使得a[l]-a[l+1]+a[l+2]-a[l+3]....a[r]最大。
解题报告:
直接dp。分以奇数为结尾和偶数为结尾两种情况分别讨论一下即可,其实这题不用set,因为只需要最大值和最小值,所以可以直接维护前缀最大值最小值即可。
AC代码:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<set>
#include<string>
#include<cmath>
#include<cstring>
#define FF first
#define SS second
#define ll long long
#define pb push_back
#define pm make_pair
using namespace std;
typedef pair<int,int> PII;
const int MAX = 2e5 + 5;
int n;
ll a[MAX],b[MAX],sum[MAX],ans=-1e18;
set<ll> ss[2];
int main()
{cin>>n;for(int i = 1; i<=n; i++) scanf("%lld",a+i);for(int i = 1; i<n; i++) {b[i] = abs(a[i]-a[i+1]);if(i%2 == 0) b[i] = -b[i];sum[i] = sum[i-1] + b[i];ans=max(ans,abs(b[i]));}ss[0].insert(0);ss[1].insert(0);for(int i = 1; i<n; i++) {if(i%2==0) {//还是得分情况,,,不知道自己在写什么if(ss[i%2].size()) ans = max(ans,sum[i] - *ss[(i%2)].begin());if(ss[!(i%2)].size()) ans = max(ans,-sum[i] + *ss[!(i%2)].rbegin()); }else {if(ss[i%2].size()) ans = max(ans,-sum[i] + *ss[(i%2)].rbegin());if(ss[!(i%2)].size()) ans = max(ans,sum[i] - *ss[!(i%2)].begin());} ss[i%2].insert(sum[i]);}cout << ans << endl;return 0 ;
}