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
function longestEvenOddSubarray ( a , n ) { let longest = 1 ; let cnt = 1 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { if ( ( a [ i ] + a [ i + 1 ] ) % 2 == 1 ) { cnt ++ ; } else { longest = Math . max ( longest , cnt ) ; cnt = 1 ; } } if ( longest == 1 ) return 0 ; return Math . max ( cnt , longest ) ; } let a = [ 1 , 2 , 3 , 4 , 5 , 7 , 8 ] ; let n = a . length ; document . write ( longestEvenOddSubarray ( a , n ) ) ;