Given a binary matrix, we can flip one column or one row, the goal is to flip zero or more times such that the sum of the number represented by the rows are maximized.
Intuition
The leading 1
s are always important than the trailing 1
s. So we make sure that 1
appears before 0
s.
Approach
The challenge is to determine when to flip the rows and flip the columns. From the intuition, we know that:
- a row is flipped only if its first bit is
0
, after flipping, the number becomes larger and cannot be flipped again. - a column is flipped only if the number of
1
s are smaller than0
s.
So we flip the rows first and the columns second.
Complexity
Time complexity: iterate matrix twice. $$ O(mn) $$
Space complexity: no extra space needed. $$ O(1) $$
Code
|
|