Longest alternative parity subsequence | C ++ 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
#include <iostream> NEW_LINE using namespace std ; int longestAlternativeSequence ( int a [ ] , int n ) { int maxi1 = 0 ; int f1 = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( ! f1 ) { if ( a [ i ] % 2 ) { 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 ) { if ( a [ i ] % 2 ) { f2 = 1 ; maxi2 ++ ; } } else { if ( a [ i ] % 2 == 0 ) { maxi2 ++ ; f2 = 0 ; } } } return max ( maxi1 , maxi2 ) ; } int main ( ) { int a [ ] = { 13 , 16 , 8 , 9 , 32 , 10 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << longestAlternativeSequence ( a , n ) ; }