Longest subarray of non | Function to find the maximum length of a subarray of 1 s after removing at most one 0 ; Stores the count of consecutive 1 's from left ; Stores the count of consecutive 1 's from right ; Traverse left to right ; If cell is non - empty ; Increase count ; If cell is empty ; Store the count of consecutive 1 's  till (i - 1)-th index ; Traverse from right to left ; Store the count of consecutive 1 s till ( i + 1 ) - th index ; Stores the length of longest subarray ; Store the maximum ; If array a contains only 1 s return n else return ans ; Driver code
def longestSubarray ( a , n ) : NEW_LINE INDENT l = [ 0 ] * ( n ) NEW_LINE r = [ 0 ] * ( n ) NEW_LINE count = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT l [ i ] = count NEW_LINE count = 0 NEW_LINE DEDENT DEDENT count = 0 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT if ( a [ i ] == 1 ) : NEW_LINE INDENT count += 1 NEW_LINE DEDENT else : NEW_LINE INDENT r [ i ] = count NEW_LINE count = 0 NEW_LINE DEDENT DEDENT ans = - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( a [ i ] == 0 ) : NEW_LINE INDENT ans = max ( ans , l [ i ] + r [ i ] ) NEW_LINE DEDENT DEDENT return ans < 0 and n or ans NEW_LINE DEDENT arr = [ 0 , 1 , 1 , 1 , 0 , 1 , 0 , 1 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestSubarray ( arr , n ) ) NEW_LINE