题目描述: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;
}
}