Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | Java program to implement the above approach ; Function to find the maximum subarray length of ones ; Stores the length , starting index and ending index of the subarrays ; S : starting index of the sub - array ; Traverse only continuous 1 s ; Calculate length of the sub - array ; v [ i ] [ 0 ] : Length of subarray v [ i ] [ 1 ] : Starting Index of subarray v [ i ] [ 2 ] : Ending Index of subarray ; If no such sub - array exists ; Traversing through the subarrays ; Update maximum length ; v [ i + 1 ] [ 1 ] - v [ i ] [ 2 ] - 1 : Count of zeros between the two sub - arrays ; Update length of both subarrays to the maximum ; Update length of both subarrays - 1 to the maximum ; Check if the last subarray has the maximum length ; Driver Code
import java . io . * ; import java . util . * ; class GFG { static int maxLen ( int A [ ] , int N ) { List < List < Integer > > v = new ArrayList < > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( A [ i ] == 1 ) { int s = i , len ; while ( i < N && A [ i ] == 1 ) { i ++ ; } len = i - s ; v . add ( Arrays . asList ( len , s , i - 1 ) ) ; } } if ( v . size ( ) == 0 ) { return - 1 ; } int ans = 0 ; for ( int i = 0 ; i < v . size ( ) - 1 ; i ++ ) { ans = Math . max ( ans , v . get ( i ) . get ( 0 ) ) ; if ( v . get ( i + 1 ) . get ( 1 ) - v . get ( i ) . get ( 2 ) - 1 == 2 ) { ans = Math . max ( ans , v . get ( i ) . get ( 0 ) + v . get ( i + 1 ) . get ( 0 ) ) ; } if ( v . get ( i + 1 ) . get ( 1 ) - v . get ( i ) . get ( 2 ) - 1 == 1 ) { ans = Math . max ( ans , v . get ( i ) . get ( 0 ) + v . get ( i + 1 ) . get ( 0 ) - 1 ) ; } } ans = Math . max ( v . get ( v . size ( ) - 1 ) . get ( 0 ) , ans ) ; return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 0 , 1 , 0 , 0 , 1 } ; int N = arr . length ; System . out . println ( maxLen ( arr , N ) ) ; } }