Problem Statement
A sequence of numbers is called a zig-zag sequence if the differences between successive numbers strictly alternate between positive and negative. The first difference (if one exists) may be either positive or negative. A sequence with fewer than two elements is trivially a zig-zag sequence.
For example, 1,7,4,9,2,5 is a zig-zag sequence because the differences (6,-3,5,-7,3) are alternately positive and negative. In contrast, 1,4,7,2,5 and 1,7,4,5,5 are not zig-zag sequences, the first because its first two differences are positive and the second because its last difference is zero.
Given a sequence of integers, sequence, return the length of the longest subsequence of sequence that is a zig-zag sequence. A subsequence is obtained by deleting some number of elements (possibly zero) from the original sequence, leaving the remaining elements in their original order.
import java.util.Random;
class ZigZag
{
static void print(int[] arr)
{
System.out.println();
for(int i=0;i lessThan arr.length;i++)
{
System.out.print(" "+arr[i]);
}
System.out.println();
}
public static void main(String[] args)
{
int[] arr ={ 70, 55, 13, 2, 99, 2, 80, 80, 80, 80, 100, 19, 7, 5, 5, 5,1000,32,32};
int n=arr.length;
int[] numb = new int[n];
int sign=0;
int i=0;
Random r=new Random();
numb[0]=1;
numb[1]=1;
if(arr[0]!=arr[1])
numb[1]=2;
print(arr);
for(i=2;i lessThan n;i++)
{
sign=arr[i-1]-arr[i-2];
print(numb);
if(sign==0 || arr[i]==arr[i-1])
{
numb[i]=numb[i-1];
continue;
}
if(sign lessThan 0 && arr[i]-arr[i-1] greaterThan 0)
{
numb[i]=numb[i-1]+1;
continue;
}
if(sign greaterThan 0 && arr[i]-arr[i-1] lessThan 0)
{
numb[i]=numb[i-1]+1;
continue;
}
if(sign lessThan 0 && arr[i]-arr[i-1] greaterThan 0)
{
numb[i]=numb[i-1];
continue;
}
if(sign lessThan 0 && arr[i]-arr[i-1] lessThan 0)
{
numb[i]=numb[i-1];
continue;
}
}
print(numb);
}
}
3 comments:
kindly explain problem and expected solution...meaning of subsequence is nto clear ...is it consective numbers of given sequence or just some numbers from array for which given constraint is satisfied...
Hi Anonymous
The input given by the user will be an array of numbers...You need to find the longest subsequence from that array which is in zigzag format...Subsequence of a given array is obtained by listing the elements of the original array in the same order but deleting some unwanted ones.
So for array :1 2 3 0 9 4
SubSequence :1 3 4
But not :1 3 2
ZigZag Subseq:1 2 0 9
Hey ...Here code is not finding max subsequence .....
Post a Comment