CF484D 把数组划分成几段,求所有段的最大值-最小值之和的最大值

本文探讨了一个幼儿园孩子分组的问题,通过最大化各组之间的社会性差异来优化分组效果。使用动态规划方法解决此问题,确保每个连续的孩子段要么是递增的要么是递减的,以实现最大的社会性总值。

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.

Input

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).

Output

Print the maximum possible total sociability of all groups.

Sample test(s)
input
5
1 2 3 1 2
output
3
input
3
3 3 3
output
0
Note

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]求遍历到i时的最大值。http://blog.youkuaiyun.com/keshuai19940722/article/details/40873581

#include<bits/stdc++.h>
#define ll long long 
using namespace std;
ll x[1000005]; 
ll dp[1000005]; 
int main(){
	int n;
	scanf("%d",&n); 
	for(int i=1;i<=n;++i)
		scanf("%I64d",&x[i]); 
	dp[0]=0;
	dp[1]=0;
	for(int i=2;i<=n;++i){
		if(x[i-1]>=x[i-2]&&x[i-1]>=x[i]){ 
			dp[i]=max(dp[i-2]+x[i-1]-x[i],dp[i-1]); //把前一段递增的最大值分出去给下一段的递减还是不分出去 
		}
		else if(x[i-1]>=x[i-2]&&x[i-1]<x[i]){
			dp[i]=dp[i-1]+x[i]-x[i-1];  //前一段递增,又放进来一个更大的数,继续递增 
		}
		else if(x[i-1]<x[i-2]&&x[i-1]>=x[i]){ 
			dp[i]=dp[i-1]+x[i-1]-x[i];  //前一段递减,又放进来一个更小的数,继续递减 
		}
		else if(x[i-1]<x[i-2]&&x[i-1]<x[i]){ 
			dp[i]=max(dp[i-2]+x[i]-x[i-1],dp[i-1]); //把前一段递减的最小值分出去给下一段的递增还是不分出去 
		}
	} 
	printf("%I64d\n",dp[n]); 
	 
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值