Suppose we have a 2D binary matrix. For any row or column in the given matrix we can flip all the bits. If we can perform any number of these operations, and that we treat each row as a binary number, we have to find the largest sum that can be made of these numbers.
So, if the input is like
then the output will be 11, as if we flip both rows we get 101 and 110, then the sum is 5 + 6 = 11
To solve this, we will follow these steps −
Let us see the following implementation to get better understanding −
class Solution: def solve(self, matrix): for r in matrix: if r == 0: for i in range(len(r)): r[i] = -r[i] + 1 for j in range(1, len(matrix)): cnt = 0 for i in range(len(matrix)): cnt += 1 if matrix[i][j] else -1 if cnt < 0: for i in range(len(matrix)): matrix[i][j] = -matrix[i][j] + 1 ans = 0 for r in matrix: a = 0 for v in r: a = 2 * a + v ans += a return ans ob = Solution() matrix = [ [0, 1, 0], [0, 0, 1] ] print(ob.solve(matrix))
[[0, 1, 0],[0, 0, 1]]