Program to find maximum sum by flipping each row elements in Python


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

010
001

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 −

  • for each row r in matrix, do
    • if r[0] is same as 0, then
      • for i in range 0 to size of r, do
        • r[i] := -r[i] + 1
  • for j in range 1 to column size of matrix, do
    • cnt := 0
    • for i in range 0 to row count of matrix, do
      • cnt := cnt + 1 if matrix[i, j] is 1 otherwise -1
    • if cnt < 0, then
      • for i in range 0 to row size of matrix, do
        • matrix[i, j] := -matrix[i, j] + 1
  • ans := 0
  • for each row r in matrix, do
    • a := 0
    • for each v in r, do
      • a := 2 * a + v
    • ans := ans + a
  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, matrix):
      for r in matrix:
         if r[0] == 0:
            for i in range(len(r)):
               r[i] = -r[i] + 1
      for j in range(1, len(matrix[0])):
         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))

Input

[[0, 1, 0],[0, 0, 1]]

Output

11

Updated on: 19-Nov-2020

174 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements