789.C Functions again

本文探讨了一个数学问题,即在一个序列中寻找特定函数的最大值。通过转化问题,将其变为求最大子段和的经典算法问题。文章详细解释了解决方案,并提供了完整的代码实现。

摘要生成于 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

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个数构成的序列,然后给出方程
在这里插入图片描述
求最大的f。

题目分析:
这道看上去很唬人(我当时就被唬住了),但其实并不难。
给出的方程可以转化为:定义一段序列b,b[i]=|a[i]-a[i+1]|*(-1)(i-1)(l<=i<r),即a中相邻两数差的绝对值乘上(-1)i-1.求这个序列b的字段和。这样,这道题目就转换为了一道求最大字段和的问题。我们可以将i的范围扩展到1一n-1,然后求出b的最大字段和。
因为f中l和r的位置不确定,因此我们要考虑两种情况:

  1. l的位置为奇数,此时b为+ - + - + - +…
  2. l的位置为偶数,此时b为- + - + - + -…

所以,我们分别求出这两种情况的最大子段和的最大值即可。
最大子段和求法参考Maximum sum

代码如下:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <map>
#include <queue>
#include <algorithm>
#include <iomanip>
#define LL long long
using namespace std;
const int N=1e5+5;
LL a[N],b[N],c[N];
int main()
{
	int n;
	scanf("%d",&n);     //因为数据量较大,输入要用scanf
	for(int i=1;i<=n;i++)
	scanf("%lld",&a[i]);
	for(int i=1;i<n;i++)
	{ //分别计算两种情况的序列
		if(i%2)
		{
			b[i]=abs(a[i]-a[i+1]);
			c[i]=-b[i];
		}
		else
		{
			c[i]=abs(a[i]-a[i+1]);
			b[i]=-c[i];
		}
	}
	LL ans=0,sum=0;     //答案有可能爆int
	for(int i=1;i<n;i++) //计算两种情况的最大字段和
	{
		sum+=b[i];
		if(sum<0) sum=0;
		ans=max(ans,sum);
	}
	sum=0;
	for(int i=1;i<n;i++)
	{
		sum+=c[i];
		if(sum<0) sum=0;
		ans=max(ans,sum);
	}
	printf("%lld\n",ans);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lwz_159

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值