Longest alternative parity subsequence | Java program to find the length of the longest alternative parity subsequence ; Function to find the longest ; Marks the starting of odd number as sequence and alternatively changes ; Finding the longest odd / even sequence ; Find odd number ; Find even number ; Length of the longest even / odd sequence ; Find odd number ; Find even number ; Answer is maximum of both odd / even or even / odd subsequence ; Driver Code
class GFG { static int longestAlternativeSequence ( int a [ ] , int n ) { int maxi1 = 0 ; int f1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( f1 % 2 != 0 ) { if ( a [ i ] % 2 == 1 ) { f1 = 1 ; maxi1 ++ ; } } else { if ( a [ i ] % 2 == 0 ) { maxi1 ++ ; f1 = 0 ; } } } int maxi2 = 0 ; int f2 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( f2 % 2 != 0 ) { if ( a [ i ] % 2 == 1 ) { f2 = 1 ; maxi2 ++ ; } } else { if ( a [ i ] % 2 == 0 ) { maxi2 ++ ; f2 = 0 ; } } } return Math . max ( maxi1 , maxi2 ) ; } public static void main ( String [ ] args ) { int a [ ] = { 13 , 16 , 8 , 9 , 32 , 10 } ; int n = a . length ; System . out . println ( longestAlternativeSequence ( a , n ) ) ; } }