题目地址:点击打开链接
思路:一共就两种情况,要么奇数位为负,要么偶数位的为负。两个分别求下最大连续子段和取较大值就行。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
ll a[maxn], v[maxn], n;
int main(void)
{
while(cin >> n)
{
for(int i = 1; i <= n; i++)
scanf("%I64d", &a[i]);
for(int i = 1; i < n; i++)
v[i] = abs(a[i+1]-a[i]);
ll ans = 0;
for(int i = 1; i < n; i++)
a[i] = i%2 ? -v[i] : v[i];
ll tmp = 0;
for(int i = 1; i < n; i++)
{
tmp += a[i];
if(tmp < 0) tmp = 0;
ans = max(ans, tmp);
}
for(int i = 1; i < n; i++)
a[i] = i%2 ? v[i] : -v[i];
tmp = 0;
for(int i = 1; i < n; i++)
{
tmp += a[i];
if(tmp < 0) tmp = 0;
ans = max(ans, tmp);
}
cout << ans << endl;
}
return 0;
}