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
def longestEvenOddSubarray ( arr , n ) : NEW_LINE INDENT longest = 1 NEW_LINE cnt = 1 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT if ( ( arr [ i ] + arr [ i + 1 ] ) % 2 == 1 ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE DEDENT else : NEW_LINE INDENT longest = max ( longest , cnt ) NEW_LINE cnt = 1 NEW_LINE DEDENT DEDENT if ( longest == 1 ) : NEW_LINE return 0 NEW_LINE return max ( cnt , longest ) NEW_LINE DEDENT arr = [ 1 , 2 , 3 , 4 , 5 , 7 , 8 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestEvenOddSubarray ( arr , n ) ) NEW_LINE