Maximum score after flipping a Binary Matrix atmost K times | Python3 program to find the maximum score after flipping a Binary Matrix atmost K times ; Function to find maximum score of matrix ; Find value of rows having first column value equal to zero ; update those rows which lead to maximum score after toggle ; Calculating answer ; check if K > 0 we can toggle if necessary . ; return max answer possible ; Driver Code ; function call to print required answer
n = 3 NEW_LINE m = 4 NEW_LINE def maxMatrixScore ( A , K ) : NEW_LINE INDENT update = { } NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if A [ i ] [ 0 ] == 0 : NEW_LINE INDENT ans = 0 NEW_LINE for j in range ( 1 , m ) : NEW_LINE INDENT ans = ans + A [ i ] [ j ] * 2 ** ( m - j - 1 ) NEW_LINE DEDENT update [ ans ] = i NEW_LINE DEDENT DEDENT for idx in update . values ( ) : NEW_LINE INDENT for j in range ( 0 , m ) : NEW_LINE INDENT A [ idx ] [ j ] = ( A [ idx ] [ j ] + 1 ) % 2 NEW_LINE DEDENT K -= 1 NEW_LINE if K <= 0 : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT ans = 0 NEW_LINE for j in range ( 0 , m ) : NEW_LINE INDENT zero , one = 0 , 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if A [ i ] [ j ] == 0 : zero += 1 NEW_LINE else : one += 1 NEW_LINE DEDENT if K > 0 and zero > one : NEW_LINE INDENT ans += zero * 2 ** ( m - j - 1 ) NEW_LINE K -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT ans += one * 2 ** ( m - j - 1 ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT A = [ [ 0 , 0 , 1 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 1 , 1 , 0 , 0 ] ] NEW_LINE K = 2 NEW_LINE print ( maxMatrixScore ( A , K ) ) NEW_LINE DEDENT