Bit flip
1 min readDec 23, 2019
861. Score After Flipping Matrix
“The idea is to flip all the rows, that has a 0 in the front.
Then for each column flip it, if the number of 0’s > number of 1's”
class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
R, C = len(A), len(A[0])
for i in range(R):
if A[i][0]==1:
new_a.append(A[i])
else:
new_a.append([int(not a) for a in A[i]])
res = [['1']*R]
for i, col in enumerate(zip(*new_a)):
if i!=0:
S = sum(col)
if S<R-S:res.append([str(int(not c)) for c in col])
else:
res.append([str(c) for c in col])
return sum(int(''.join(col), 2) for col in zip(*res))
Or more tight
class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
new_a = [row if row[0] else [int(not a) for a in row] for row in A]
a_by_col = [[str(c) for c in col] if sum(col)>len(A)-sum(col) else
[str(int(not c)) for c in col] for col in zip(*new_a)]
return sum(int(''.join(col), 2) for col in zip(*a_by_col))