Maximum difference of zeros and ones in binary string | Set 2 ( O ( n ) time ) | Returns the length of substring with maximum difference of zeroes and ones in binary string ; traverse a binary string from left to right ; add current value to the current_sum according to the Character if it ' s ▁ ' 0 ' add 1 else -1 ; update maximum sum ; return - 1 if string does not contain any zero that means all ones otherwise max_sum ; Driven Program
def findLength ( string , n ) : NEW_LINE INDENT current_sum = 0 NEW_LINE max_sum = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT current_sum += ( 1 if string [ i ] == '0' else - 1 ) NEW_LINE if current_sum < 0 : NEW_LINE INDENT current_sum = 0 NEW_LINE DEDENT max_sum = max ( current_sum , max_sum ) NEW_LINE DEDENT return max_sum if max_sum else 0 NEW_LINE DEDENT s = "11000010001" NEW_LINE n = 11 NEW_LINE print ( findLength ( s , n ) ) NEW_LINE