Longest subarray with all even or all odd elements | C # implementation for the above approach ; Function to calculate longest subString with odd or even elements ; Initializing dp ; Initializing dp with 1 ; ans will store the readonly 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 readonly answer ; Driver code ; Input ; Function call
using System ; public class GFG { static int longestOddEvenSubarray ( int [ ] A , int N ) { int dp ; dp = 1 ; int ans = 1 ; for ( int 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 ; } public static void Main ( String [ ] args ) { int [ ] A = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = A . Length ; Console . Write ( longestOddEvenSubarray ( A , N ) ) ; } }