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
function LongestOddEvenSubarray ( A , N ) { let dp ; dp = 1 ; let ans = 1 ; for ( let i = 1 ; i < N ; i ++ ) { if ( ( A [ i ] % 2 == 0 && A [ i - 1 ] % 2 == 0 ) || ( A [ i ] % 2 != 0 && A [ i - 1 ] % 2 != 0 ) ) { dp = dp + 1 ; ans = Math . max ( ans , dp ) ; } else dp = 1 ; } return ans ; } let A = [ 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 ] ; let N = A . length ; document . write ( LongestOddEvenSubarray ( A , N ) ) ;