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 1s are always important than the trailing 1s. So we make sure that 1 appears before 0s.
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
1s are smaller than0s.
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
| |