Length of the longest alternating even odd subarray | C ++ program to find the Length of the longest alternating even odd subarray ; Function to find the longest subarray ; Length of longest alternating subarray ; Iterate in the array ; increment count if consecutive elements has an odd sum ; Store maximum count in longest ; Reinitialize cnt as 1 consecutive elements does not have an odd sum ; Length of ' longest ' can never be 1 since even odd has to occur in pair or more so return 0 if longest = 1 ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int longestEvenOddSubarray ( int a [ ] , int n ) { int longest = 1 ; int cnt = 1 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { if ( ( a [ i ] + a [ i + 1 ] ) % 2 == 1 ) { cnt ++ ; } else { longest = max ( longest , cnt ) ; cnt = 1 ; } } if ( longest == 1 ) return 0 ; return max ( cnt , longest ) ; } int main ( ) { int a [ ] = { 1 , 2 , 3 , 4 , 5 , 7 , 8 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; cout << longestEvenOddSubarray ( a , n ) ; return 0 ; }