Minimum flips required to keep all 1 s together in a Binary string | Python implementation for Minimum number of flips required in a binary string such that all the 1 aTMs are together ; Length of the binary string ; Initial state of the dp dp [ 0 ] [ 0 ] will be 1 if the current bit is 1 and we have to flip it ; Initial state of the dp dp [ 0 ] [ 1 ] will be 1 if the current bit is 0 and we have to flip it ; dp [ i ] [ 0 ] = Flips required to make all previous bits zero + Flip required to make current bit zero ; dp [ i ] [ 1 ] = minimum flips required to make all previous states 0 or make previous states 1 satisfying the condition ; Minimum of answer and flips required to make all bits 0 ; Driver code
def minFlip ( a ) : NEW_LINE INDENT n = len ( a ) NEW_LINE dp = [ [ 0 , 0 ] for i in range ( n ) ] NEW_LINE dp [ 0 ] [ 0 ] = int ( a [ 0 ] == '1' ) NEW_LINE dp [ 0 ] [ 1 ] = int ( a [ 0 ] == '0' ) NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] [ 0 ] = dp [ i - 1 ] [ 0 ] + int ( a [ i ] == '1' ) NEW_LINE dp [ i ] [ 1 ] = min ( dp [ i - 1 ] ) + int ( a [ i ] == '0' ) NEW_LINE DEDENT answer = 10 ** 18 NEW_LINE for i in range ( n ) : NEW_LINE INDENT answer = min ( answer , dp [ i ] [ 1 ] + dp [ n - 1 ] [ 0 ] - dp [ i ] [ 0 ] ) NEW_LINE DEDENT return min ( answer , dp [ n - 1 ] [ 0 ] ) NEW_LINE DEDENT s = "1100111000101" NEW_LINE print ( minFlip ( s ) ) NEW_LINE