Functions again

本文介绍了一种解决特定数学问题的方法,即寻找数组中定义的Uzhlyandian函数的最大值。通过将原问题转化为计算相邻元素差的绝对值,并结合奇偶性判断,实现了有效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

题意:给出一个n,表示数组a的元素个数,接下来n个数为a【i】,,问f最大值是什末。

思路:这个题跟以前做过的max sum 非常像,其实另开一个数组b,数组b中存的是a[ i ]- a[i+1],然后不管 l 和 r 是多少,第一个pow(-1,i-l)为正,第二个为负,得奇数为负,偶数为正,用一个数k记录一下正负即可,我们见假设从1开始,如果发现加的过程中sum值为负数,这种情况怎末加也不会最大。然后从第二个元素开始加,实时更新一下maxx的值最后输出来即可,代码如下:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#define N 100010
using namespace std;
long long int a[N],b[N];
int main()
{
    int n,i;
    long long sum,maxx,k,v;
    while(~scanf("%d",&n)&&n)
    {
        sum=maxx=k=0;
        v=1;
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        for(i=1;i<=n;i++)
        scanf("%lld",&a[i]);
        for(i=1;i<n;i++)
            b[i]=abs(a[i]-a[i+1]);
        for(i=v;i<n;i++)
        {
            if(k%2==0)
            {
                sum=sum+b[i]; //k是偶数相加
                k++;
            }
            else
            {
                sum=sum-b[i];//k是奇数相减
                k++;
            }
            if(sum>maxx)
                maxx=sum;   //更新maxx的值
            if(sum<0)       //如果sum小与0,舍弃这种情况
            {
                sum=0;
                k=0;
                i=v++;
            }
        }
        printf("%lld\n",maxx);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值