Codeforces-788A Functions again(dp)

A. Functions again
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

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.


题解:定义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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值