我需要写一个method that needs to return the length of the longest subsequence of sequence that is a zig-zag sequence.
算法方法应该是动态编程。
如果连续数字之间的差异在正负之间严格交替,则数字序列称为之字形序列。第一个差异(如果存在)可以是正面的也可以是负面的。
Eg - 1,7,4,9,2,5 is a zig-zag sequence
because the differences (6,-3,5,-7,3) are alternately positive and negative.
1,4,7,2,5 is not a zig-zag sequence.
我的代码:
public static int longestZigZag(int[] seq){
int len = seq.length;
int[] count= new int[len];
for(int i=0;i<len;i++)
count[i]=1;
for(int i=1;i<len;i++){
int k = (int)Math.pow(-1, i+1);
if(seq[i]>(k*seq[i-1])){
count[i]=count[i-1]+1;
}
}
int max=1;
for(int i=0;i<len;i++)
if(count[i]>max)
max=count[i];
return max;
}
解释:
对应于每个元素,我有一个count
元素,它代表了直到那个点的连续交替序列。
seq: 1, 7, 4, 9, 2, 5
count: 1, 1, 1, 1, 1, 1
i=1 7 > 1 count[1]= count[0]+1 = 2
i=2 4 > -7 count[2]= count[1]+1 = 3
i=1 9 > 4 count[3]= count[2]+1 = 4
i=1 2 > -9 count[4]= count[3]+1 = 5
i=1 5 > 2 count[5]= count[4]+1 = 6
之后,我只是打印计数数组的最大值。
错误:
以上适用于
{ 1, 7, 4, 9, 2, 5 } -> 6
{ 1, 17, 5, 10, 13, 15, 10, 5, 16, 8 } -> 7
但是,它给出了错误的结果
{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } gives 9 but should be 2.
{ 70, 55, 13, 2, 99, 2, 80, 80, 80, 80, 100, 19, 7, 5,
5, 5, 1000, 32, 32 } gives 2 but should be 8.