Interview Question
Software DevelopersCountry: -
Take the input as Integer Array.
Store the position where the first greater than or less than occurs (keep skipping if the elements are equal). Store the comparison value i.e. 1 or -1 in first
From that point on, find the next less than, greater than (next in this case) and compare it the last stored i.e first in this case.
At then end, the number of less thans and greater thans are found. Return result+!
public class ZigZagArrayMaxDemo {
public static int maxZigZagLength(Integer[] input) {
if(input.length ==0 ) throw new IllegalArgumentException("array length is 0");
int result = 0;
int first = 0;
int startIndex = 0;
for(int i = 0; i < input.length - 1; i++) {
first = input[i].compareTo(input[i+1]);
if(first !=0) {
startIndex = i+1;
result = 1;
break;
}
}
if(first == 0) return 0;
int next;
for (int i = startIndex; i < input.length - 1; i++) {
next = input[i].compareTo(input[i+1]);
if(next == 0) continue;
if((next != first)) {
result++;
first = next;
}
}
return result+1;
}
public static void main(String[] args) {
Integer[] inputArray = {1,42,54,20,1 };
System.out.println(maxZigZagLength(inputArray));
}
}
Please let me know if you find any bugs in approach
- siva.sai.2020 November 23, 2015