#861

Score After Flipping Matrix

Medium
ArrayGreedyBit ManipulationMatrixGreedyBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(2^(m+n))
O(m * n)
Space
O(1)
O(1)
💡

Intuition

Time O(m * n)Space O(1)

Instead of toggling every row and column, we can maximize the score by ensuring the first bit of each row is always 1. This can be achieved by toggling rows based on the first column's values.

⚙️

Algorithm

3 steps
  1. 1Step 1: For each row, if the first element is 0, toggle the entire row.
  2. 2Step 2: For each column, count the number of 1's and 0's. If there are more 0's than 1's, toggle that column.
  3. 3Step 3: Calculate the score by interpreting each row as a binary number and summing them up.
solution.py23 lines
1# Full working Python code
2def maxScore(grid):
3    m, n = len(grid), len(grid[0])
4    # Toggle rows to ensure first column is all 1s
5    for i in range(m):
6        if grid[i][0] == 0:
7            for j in range(n):
8                grid[i][j] ^= 1
9    # Toggle columns based on counts
10    for j in range(1, n):
11        count = sum(grid[i][j] for i in range(m))
12        if count < m / 2:
13            for i in range(m):
14                grid[i][j] ^= 1
15    # Calculate the score
16    score = 0
17    for i in range(m):
18        row_value = 0
19        for j in range(n):
20            row_value = (row_value << 1) | grid[i][j]
21        score += row_value
22    return score
23

Complexity note: The time complexity is linear because we only iterate through the matrix a few times, making it efficient for the given constraints.

  • 1Maximizing the first bit of each row significantly increases the score.
  • 2Toggling rows based on the first column simplifies the problem.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.