Length of longest consecutive ones by at most one swap in a Binary String | Function to calculate the length of the longest consecutive 1 's ; To count all 1 's in the string ; To store cumulative 1 's ; Counting cumulative 1 's from left ; If 0 then start new cumulative one from that i ; perform step 3 of the approach ; step 3 ; Driver Code ; string
def maximum_one ( s , n ) : NEW_LINE INDENT cnt_one = 0 NEW_LINE cnt , max_cnt = 0 , 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT cnt_one += 1 NEW_LINE cnt += 1 NEW_LINE DEDENT else : NEW_LINE INDENT max_cnt = max ( max_cnt , cnt ) NEW_LINE cnt = 0 NEW_LINE DEDENT DEDENT max_cnt = max ( max_cnt , cnt ) NEW_LINE left = [ 0 ] * n NEW_LINE right = [ 0 ] * n NEW_LINE if ( s [ 0 ] == '1' ) : NEW_LINE INDENT left [ 0 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT left [ 0 ] = 0 NEW_LINE DEDENT if ( s [ n - 1 ] == '1' ) : NEW_LINE INDENT right [ n - 1 ] = 1 NEW_LINE DEDENT else : NEW_LINE INDENT right [ n - 1 ] = 0 NEW_LINE DEDENT for i in range ( 1 , n ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT left [ i ] = left [ i - 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT left [ i ] = 0 NEW_LINE DEDENT DEDENT for i in range ( n - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( s [ i ] == '1' ) : NEW_LINE INDENT right [ i ] = right [ i + 1 ] + 1 NEW_LINE DEDENT else : NEW_LINE INDENT right [ i ] = 0 NEW_LINE DEDENT DEDENT for i in range ( 1 , n - 1 ) : NEW_LINE INDENT if ( s [ i ] == '0' ) : NEW_LINE INDENT sum = left [ i - 1 ] + right [ i + 1 ] NEW_LINE if ( sum < cnt_one ) : NEW_LINE INDENT max_cnt = max ( max_cnt , sum + 1 ) NEW_LINE DEDENT else : NEW_LINE INDENT max_cnt = max ( max_cnt , sum ) NEW_LINE DEDENT DEDENT DEDENT return max_cnt NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT s = "111011101" NEW_LINE print ( maximum_one ( s , len ( s ) ) ) NEW_LINE DEDENT