Lets say we have an array {1, 1, 2, 3, 6, 5, 5, 4, 6}
Find the longest contiguous odd/even or even/odd subsequence in the array.
Answer is 5: {1, 2, 3, 6, 5}
My idea is to find two subsequence
- starting number is odd
- starting number is even
return the max of both
The code i wrote finds the longest subsequence, but is not contiguous
public static int longestAlternativeSequence(int[] a, int n) {
int maxOdd = 0; //Max subsequence starting with odd Number
int maxEven = 0; //Max subsequence starting with even Number
int odd = 0;
int even = 0;
for (int i = 0; i < n; i++) {
if (odd == 0) { // first number has to be odd
if (a[i] % 2 == 1) {
odd = 1;
maxOdd++;
}
}
else {
if (a[i] % 2 == 0) {
odd = 0;
maxOdd++;
}
}
}
for (int i = 0; i < n; i++) {
if (even == 0) { //first number has to be even
if (a[i] % 2 == 0) {
even = 1;
maxEven++;
}
}
else {
if (a[i] % 2 == 1) {
even = 1;
maxEven++;
}
}
}
return Math.max(maxOdd, maxEven);
}
public static void main(String[] args) {
int a[] = {1, 1, 2, 3, 6, 5, 5, 4, 6};
int n = a.length;
System.out.println(longestOddEven(a, n)); //returns 6
}