Longest subarray with all even or all odd elements | Function to calculate longest substring with odd or even elements ; Initializing dp Initializing dp with 1 ; ans will store the final answer ; Traversing the array from index 1 to N - 1 ; Checking both current and previous element is even or odd ; Updating dp with ( previous dp value ) + 1 ; Storing max element so far to ans ; Returning the final answer ; Input ; Function call
def LongestOddEvenSubarray ( A , N ) : NEW_LINE INDENT dp = 1 NEW_LINE ans = 1 NEW_LINE for i in range ( 1 , N ) : NEW_LINE INDENT if ( ( A [ i ] % 2 == 0 and A [ i - 1 ] % 2 == 0 ) or ( A [ i ] % 2 != 0 and A [ i - 1 ] % 2 != 0 ) ) : NEW_LINE INDENT dp = dp + 1 NEW_LINE ans = max ( ans , dp ) NEW_LINE DEDENT else : NEW_LINE INDENT dp = 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT A = [ 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 ] NEW_LINE N = len ( A ) NEW_LINE print ( LongestOddEvenSubarray ( A , N ) ) NEW_LINE