Optimally accommodate 0 s and 1 s from a Binary String into K buckets | Function to find the minimum required sum using dynamic programming ; If both start and bucket reached end then return 0 else that arrangement is not possible so return INT_MAX ; Corner case ; If state if already calculated then return its answer ; Start filling zeroes and ones which to be accommodated in jth bucket then ans for current arrangement will be ones * zeroes + recur ( i + 1 , bucket + 1 ) ; If this arrangement is not possible then don 't calculate further ; Function to initialize the dp and call solveUtil ( ) method to get the answer ; Start with 0 - th index and 1 bucket ; Driver code ; K buckets
def solveUtil ( start , bucket , str1 , K , dp ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE if ( start == N ) : NEW_LINE INDENT if ( bucket == K ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT return 10 ** 9 NEW_LINE DEDENT if ( bucket == K ) : NEW_LINE INDENT return 10 ** 9 NEW_LINE DEDENT if ( dp [ start ] [ bucket ] != - 1 ) : NEW_LINE INDENT return dp [ start ] [ bucket ] NEW_LINE DEDENT zeroes = 0 NEW_LINE ones = 0 NEW_LINE ans = 10 ** 9 NEW_LINE for i in range ( start , N ) : NEW_LINE INDENT if ( str1 [ i ] == '1' ) : NEW_LINE INDENT ones += 1 NEW_LINE DEDENT else : NEW_LINE INDENT zeroes += 1 NEW_LINE DEDENT if ( ones * zeroes > ans ) : NEW_LINE INDENT break NEW_LINE DEDENT temp = solveUtil ( i + 1 , bucket + 1 , str1 , K , dp ) NEW_LINE if ( temp != 10 ** 9 ) : NEW_LINE INDENT ans = min ( ans , temp + ( ones * zeroes ) ) NEW_LINE DEDENT DEDENT dp [ start ] [ bucket ] = ans NEW_LINE return ans NEW_LINE DEDENT def solve ( str1 , K ) : NEW_LINE INDENT N = len ( str1 ) NEW_LINE dp = [ [ - 1 for i in range ( K ) ] for i in range ( N ) ] NEW_LINE ans = solveUtil ( 0 , 0 , str1 , K , dp ) NEW_LINE if ans == 10 ** 9 : NEW_LINE INDENT return - 1 NEW_LINE DEDENT else : NEW_LINE INDENT return ans NEW_LINE DEDENT DEDENT s = "0101" NEW_LINE S = [ i for i in s ] NEW_LINE K = 2 NEW_LINE print ( solve ( S , K ) ) NEW_LINE