Longest subarray with all even or all odd elements | Java program for the above approach ; 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
import java . io . * ; class GFG { static int LongestOddEvenSubarray ( int A [ ] , int N ) { int dp [ ] = new int [ N ] ; dp [ 0 ] = 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 [ i ] = dp [ i - 1 ] + 1 ; } else dp [ i ] = 1 ; } for ( int i = 0 ; i < N ; i ++ ) ans = Math . max ( ans , dp [ i ] ) ; return ans ; } public static void main ( String [ ] args ) { int A [ ] = { 2 , 5 , 7 , 2 , 4 , 6 , 8 , 3 } ; int N = A . length ; System . out . println ( LongestOddEvenSubarray ( A , N ) ) ; } }