Maximize length of Subarray of 1 's after removal of a pair of consecutive Array elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void maxLengthOf1s ( vector < int > arr , int n ) { vector < int > prefix ( n , 0 ) ; for ( int i = 2 ; i < n ; i ++ ) { if ( arr [ i - 2 ] == 1 ) prefix [ i ] = prefix [ i - 1 ] + 1 ; else prefix [ i ] = 0 ; } vector < int > suffix ( n , 0 ) ; for ( int i = n - 3 ; i >= 0 ; i -- ) { if ( arr [ i + 2 ] == 1 ) suffix [ i ] = suffix [ i + 1 ] + 1 ; else suffix [ i ] = 0 ; } int ans = 0 ; for ( int i = 0 ; i < n - 1 ; i ++ ) { ans = max ( ans , prefix [ i + 1 ] + suffix [ i ] ) ; } cout << ans << " STRNEWLINE " ; } int main ( ) { int n = 6 ; vector < int > arr = { 1 , 1 , 1 , 0 , 1 , 1 } ; maxLengthOf1s ( arr , n ) ; return 0 ; }