Skip to main content
Back to problems
#861
Medium Algorithms

Score after flipping matrix

Array Greedy Bit Manipulation Matrix
80.3% acceptance
Feb 22, 2026
2480
226
You are given an m x n binary matrix grid. A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's). Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. Return the highest possible score after making any number of moves (including zero moves).

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
/*
 * You are given an m x n binary matrix grid.
 * A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).
 * Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.
 * Return the highest possible score after making any number of moves (including zero moves).
 * Example 1:
 * Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
 * Output: 39
 * Explanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
 * Example 2:
 * Input: grid = [[0]]
 * Output: 1
 * Constraints:
 * m == grid.length
 * n == grid[i].length
 * 1 <= m, n <= 20
 * grid[i][j] is either 0 or 1.
 */

impl Solution {
  pub fn matrix_score(mut grid: Vec<Vec<i32>>) -> i32 {
    let m = grid.len();
    let n = grid[0].len();
    // Step 1: Flip rows so first column is all 1
    for i in 0..m {
      if grid[i][0] == 0 {
        for j in 0..n { grid[i][j] ^= 1; }
      }
    }
    // Step 2: For each column, ensure > m/2 ones
    for j in 1..n {
      let ones = grid.iter().filter(|r| r[j] == 1).count();
      if ones < m - ones {
        for i in 0..m { grid[i][j] ^= 1; }
      }
    }
    // Calculate score
    grid.iter().map(|row| {
      row.iter().fold(0i32, |acc, &b| acc * 2 + b)
    }).sum()
  }
}