Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | Javascript program to find the maximum count of 1 s ; If arr [ i - 2 ] = = 1 then we increment the count of occurences of 1 's ; Else we initialise the count with 0 ; If arr [ i + 2 ] = = 1 then we increment the count of occurences of 1 's ; Else we initialise the count with 0 ; We get the maximum count by skipping the current and the next element . ; Driver code
function maxLengthOf1s ( arr , n ) { let prefix = new Array ( n ) ; prefix . fill ( 0 ) ; for ( let i = 2 ; i < n ; i ++ ) { if ( arr [ i - 2 ] == 1 ) prefix [ i ] = prefix [ i - 1 ] + 1 ; else prefix [ i ] = 0 ; } let suffix = new Array ( n ) ; suffix . fill ( 0 ) ; for ( let i = n - 3 ; i >= 0 ; i -- ) { if ( arr [ i + 2 ] == 1 ) suffix [ i ] = suffix [ i + 1 ] + 1 ; else suffix [ i ] = 0 ; } let ans = 0 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { ans = Math . max ( ans , prefix [ i + 1 ] + suffix [ i ] ) ; } document . write ( ans ) ; } let n = 6 ; let arr = [ 1 , 1 , 1 , 0 , 1 , 1 ] ; maxLengthOf1s ( arr , n ) ;