method that needs to return the length of the longest subsequence of sequence that is a zig-zag sequence.
The algorithmic approach should be dynamic programmingを書く必要があります。
連続する数の差が正と負の間で厳密に交互になる場合、数列はジグザグ数列と呼ばれます。最初の差異 (存在する場合) は、正または負のいずれかです。
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.