In a kindergarten, the children are being divided into groups. The teacher put the children in a line and associated each child with his or her integer charisma value. Each child should go to exactly one group. Each group should be a nonempty segment of consecutive children of a line. A group's sociability is the maximum difference of charisma of two children in the group (in particular, if the group consists of one child, its sociability equals a zero).
The teacher wants to divide the children into some number of groups in such way that the total sociability of the groups is maximum. Help him find this value.
The first line contains integer n — the number of children in the line (1 ≤ n ≤ 106).
The second line contains n integers ai — the charisma of the i-th child ( - 109 ≤ ai ≤ 109).
Print the maximum possible total sociability of all groups.
5 1 2 3 1 2
3
3 3 3 3
0
In the first test sample one of the possible variants of an division is following: the first three children form a group with sociability 2, and the two remaining children form a group with sociability 1.
In the second test sample any division leads to the same result, the sociability will be equal to 0 in each group.
题意:把序列分成连续的若干组,每组的权值是最大值和最小值的差,问所有组的权值和的最大值。
思路:首先每组肯定是取两边的数进行计算,因为多余的没有用,然后每次记录dp[i]+val[i+1]和dp[i]-val[i+1]表示第i+1个数是加的还是减的,在o(n)的复杂度内每次去这个值的最大值。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
ll num[1000010],ans;
int main()
{
int T,t,n,m,i,j,k;
ll ans=0,a=-1e9,b=-1e9,val;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%I64d",&val);
a=max(a,ans+val);
b=max(b,ans-val);
ans=max(ans,a-val);
ans=max(ans,b+val);
}
printf("%I64d\n",ans);
}