Longest subarray with all even or all odd elements | Function to calculate longest substring with odd or even elements ; Initializing dp [ ] ; Initializing dp [ 0 ] 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 [ i ] with dp [ i - 1 ] + 1 ; Storing max element to ans ; Returning the final answer ; Driver Code ; Input ; Function call
def LongestOddEvenSubarray ( A , N ) : NEW_LINE INDENT dp = [ 0 for i in range ( N ) ] NEW_LINE dp [ 0 ] = 1 NEW_LINE ans = 1 NEW_LINE for i in range ( 1 , N , 1 ) : 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 [ i ] = dp [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT dp [ i ] = 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT ans = max ( ans , dp [ i ] ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 ] NEW_LINE N = len ( A ) NEW_LINE print ( LongestOddEvenSubarray ( A , N ) ) NEW_LINE DEDENT