Codeforces Round #407 (Div. 2) C. Functions again【最长子段和】

C. 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 land 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
Copy
5
1 4 2 3 1
output
Copy
3
input
Copy
4
1 5 4 7
output
Copy
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.



题意:Array b 有n-1个数,选择从某个数开始,每次- + - + - + , 求最大连续子段和


思路:

1.对于每个数正负号确定的情况下,出门搜:DP求解最大连续子段和

2.那么序列B的每个数无非是 + or - , 求出相应的数组求最大连续zui段和

#include<bits/stdc++.h>
#define PI acos(-1.0)
#define pb push_back
using namespace std;
typedef long long ll;

const int N=1e5+5;
const int MOD=1e9+7;
const int INF=0x3f3f3f3f;
ll a[N];
ll b[N];
ll c[N];
int main(void){
    int n;
    cin >>n;
    for(int i=1;i<=n;i++)   scanf("%I64d",&a[i]);
    for(int i=1;i<=n-1;i++){
        b[i]=abs(a[i]-a[i+1]);
        if(i%2==0)  b[i]=-b[i] ;
    }

    for(int i=1;i<=n-1;i++)
        c[i]=-b[i];

    ll mx=0,sum=0;
    for(int i=1;i<=n-1;i++){
        sum+=b[i];
        if(sum<0)   sum=0;
        mx=max(mx,sum);
    }
    sum=0;
    for(int i=1;i<=n-1;i++){
        sum+=c[i];
        if(sum<0)   sum=0;
        mx=max(mx,sum);
    }

    cout << mx << endl;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/haipai1998/article/details/80025553