861. Score After Flipping Matrix

We have a two dimensional matrix A where each value is 0 or 1.

A move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s.

After making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers.

Return the highest possible score.

 

Example 1:

Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

 

Note:

  1. 1 <= A.length <= 20
  2. 1 <= A[0].length <= 20
  3. A[i][j] is 0 or 1.

Rust Solution

struct Solution;

impl Solution {
    fn matrix_score(a: Vec<Vec<i32>>) -> i32 {
        let n = a.len();
        let m = a[0].len();
        let mut res = n << (m - 1);
        for j in 1..m {
            let mut x = Self::sum_col(j, &a, n);
            x = x.max(n - x);
            res += x << (m - 1 - j);
        }
        res as i32
    }
    fn sum_col(j: usize, a: &[Vec<i32>], n: usize) -> usize {
        let mut res = 0;
        for i in 0..n {
            res += if a[i][j] == a[i][0] { 1 } else { 0 };
        }
        res as usize
    }
}

#[test]
fn test() {
    let a = vec_vec_i32![[0, 0, 1, 1], [1, 0, 1, 0], [1, 1, 0, 0]];
    let res = 39;
    assert_eq!(Solution::matrix_score(a), res);
    let a = vec_vec_i32![[0, 1], [0, 1], [0, 1], [0, 0]];
    let res = 11;
    assert_eq!(Solution::matrix_score(a), res);
}

Having problems with this solution? Click here to submit an issue on github.