TopCoder—ZigZag

题目描述:http://community.topcoder.com/stat?c=problem_statement&pm=1259&rd=4493

题目大意如下——定义Zig-Zag序列:相连数字之间的差严格地正数和负数之间波动,不能是0。例如,(1,7,4,9,2,5)是Zig-Zag序列,而(1,4,7,2,5)和(1,7,4,5,5)不是Zig-Zag序列。现在给定一串序列,求其中最长的Zig-Zag子序列的长度。

思路:和求解最长上升子序列的思想一样,len[i]表示以num[i]结尾的最长Zig-Zag子序列长度,len[i]=max { len[j]+1 | 1<=j<i&&num[i]和以num[j]结尾的Zig-Zag子序列构成合法的Zig-Zag子序列},要注意的是,对相同元素序列地特判。

public class ZigZag {
	public int longestZigZag(int[] sequence){
		if(sequence.length==1) return 1;
		int[] pre = new int[sequence.length];  
		int[] len = new int[sequence.length];
		pre[0] = 0;
		len[0] = 1;
		if(sequence[0] != sequence[1]){
			pre[1] = 0;
			len[1] = 2;
		}
		else{
			pre[1] = 1;
			len[1] = 1;
		}
		
		int ans = len[1];
		for(int i=2;i<sequence.length;i++)
		{	int tmp = -1;
			for(int j=0;j<i;j++)
			{
				if(j==pre[j]){
					if(sequence[i]!=sequence[j]){
						if(len[j]+1>tmp){
							tmp  = len[j]+1;
							pre[i] = j;
						}
					}else{
						if(1>tmp){
							tmp = 1;
							pre[i] = i;
						}
					}
				}
				else
				{
					if((sequence[i]>sequence[j])&&(sequence[pre[j]]>sequence[j])){
						if(len[j]+1>tmp){
							tmp = len[j]+1;
							pre[i] = j;
						}
					}else if((sequence[i]<sequence[j])&&(sequence[pre[j]]<sequence[j])){
						if(len[j]+1>tmp){
							tmp = len[j]+1;
							pre[i] = j;
						}
					}
				}
			}
			len[i] = tmp;
			if(len[i]>ans) ans = len[i];
		}
		return ans;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值