Flip Columns For Maximum Number of Equal Rows in Python

PythonServer Side ProgrammingProgramming

Suppose we have a matrix consisting of 0s and 1s, we can choose any number of columns in the matrix and flip every cell in that column. converting a cell changes the value of that cell from 0 to 1 or from 1 to 0. we have to find the maximum number of rows that have all values equal after some number of flips. So if the matrix is like −

000
001
110

The output will be 2. This is because after converting values in the first two columns, the last two rows have equal values.

To solve this, we will follow these steps −

  • x := matrix, m := number of rows and n := number of columns and r := 0
  • for each element i in x
    • c := 0
    • a := a list for all elements l in i, insert l XOR i
    • for each element j in x
      • if j = i or j = a, then increase c by 1
    • r := max of c and r
  • return r

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def maxEqualRowsAfterFlips(self, matrix):
      x = matrix
      m = len(matrix)
      n = len(matrix[0] )
      r =0
      for i in x:
         c=0
         a=[l ^ 1 for l in i]
         for j in x:
            if j== i or j ==a:
               c+=1
         r=max(c, r)
      return r
ob = Solution()
print(ob.maxEqualRowsAfterFlips([[0,0,0],[0,0,1],[1,1,0]]))

Input

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

Output

2
raja
Published on 30-Apr-2020 12:18:09
Advertisements