Score After Flipping Matrix

Problem Id: 861 Difficulty: Medium


Intuition

Solution


class Solution:
    def matrixScore(self, A: List[List[int]]) -> int:
        for i in range(len(A)):
            if A[i][0] == 0:
                for j in range(len(A[i])):
                    A[i][j] = 0 if A[i][j] else 1
        for j in range(1, len(A[0])):
            if self.count_column(A, j) < len(A) / 2:
                self.flip_column(A, j)

        ans = 0
        for row in A:
            tmp = 0
            for i in row:
                tmp = (tmp << 1) + i
            ans += tmp
        return ans

    def flip_column(self, A, i):
        for row in A:
            row[i] = 0 if row[i] else 1

    def count_column(self, A, i):
        return sum([row[i] for row in A])