You are given an m x n
binary matrix grid
. We can flip the matrix’s rows and columns. A row or column flip means turning all the 0s into 1s and all the 1s into 0s. Our goal is to maximize the score after flipping.
The score of the matrix is calculated by treating each row as a binary number and interpreting it as an integer. The final score is the sum of these integers.
m x n
where both m
and n
are at least 1
.1
would be most beneficial. Following that, column flipping can help to ensure the maximum sum for the remaining bits.1
:
0
.1
s in each column (excluding the most significant bit).0
s in a column is more than the count of 1
s, flip that column.Let’s write the Python code to solve this:
def matrixScore(grid):
# Step 1: Ensure the most significant bit (leftmost bit) is 1 for all rows
for row in grid:
if row[0] == 0:
for j in range(len(row)):
row[j] ^= 1
# Step 2: Optimize the remaining columns (Excluding the first column)
num_rows = len(grid)
num_cols = len(grid[0])
for j in range(1, num_cols):
col_sum = sum(grid[i][j] for i in range(num_rows))
# If more than half the rows have 0's in this column j, flip this column
if col_sum < num_rows / 2:
for i in range(num_rows):
grid[i][j] ^= 1
# Step 3: Calculate the final score
score = 0
for row in grid:
# Interpret the binary number the row represents and add to the total score
score += int(''.join(map(str, row)), 2)
return score
O(m * n)
as we may need to flip each bit in the row.O(m * n)
as we potentially flip each cell in the column.O(m * n)
for constructing binary strings and converting them to integers.Thus, the overall time complexity is O(m * n)
where m
is the number of rows and n
is the number of columns. This is efficient given that each element in the grid needs to be considered for the optimal result.
This approach ensures we maximize the score by aiming to have the most significant bits as 1
and then optimizing the remaining bits to contribute maximally to the score.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?