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.
题解:定义dp[i][j]为遍历到第i个点,且终点为i的区间起点的位置是偶数(0)/奇数(1)的状态。
假设i%2==0,他的状态只会与i-1的状态相关:①区间[l,i-1]种l%2==0,那么dp[i][0]=max(dp[i-1][0]+a[i],a[i]),等同于f(l,i)=max(f(l,i-1)+a[i],a[i]),
因为对于dp[i][0]可以有2种选择:将a[i]接在上一个区间的后面或者将a[i]作为新的区间的头部
②区间[l,i-1]中l%2==1,那么dp[i][1]=dp[i-1][1]-a[i],等同于f(l,i)=f(l,i-1)-a[i],对于dp[i][1]只有一种选择:将a[i]接在上一个区间的后面,
因为i是偶数,不能作为起始位置是奇数的区间的头部
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MX = 1e5 + 5;
LL a[MX],dp[MX][2];
int main(){
int n;
//freopen("in.txt","r",stdin);
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%I64d",&a[i]);
for(int i=1;i<n;i++) {
a[i]=abs(a[i]-a[i+1]);
}
dp[1][1]=a[1];
dp[1][0]=0;
LL ans=a[1];
for(int i=2;i<n;i++){
if(i%2){
dp[i][0]=dp[i-1][0]-a[i];
dp[i][1]=max(a[i],dp[i-1][1]+a[i]);
ans=max(ans,max(dp[i][0],dp[i][1]));
}
else{
dp[i][0]=max(a[i],dp[i-1][0]+a[i]);
dp[i][1]=dp[i-1][1]-a[i];
ans=max(ans,max(dp[i][0],dp[i][1]));
}
}
printf("%I64d\n",ans);
return 0;
}