Score After Flipping Matrix

medium array greedy bit manipulation matrix

Problem

Given a 0/1 matrix where each row encodes a binary number, you may toggle any whole row or column. Maximize the sum of the row values.

Inputgrid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output39
Flip rows that begin with 0, then flip each column where 0s ≥ 1s.

def matrixScore(grid):
    m, n = len(grid), len(grid[0])
    total = m * (1 << (n - 1))  # leftmost column all 1s
    for j in range(1, n):
        ones = sum(1 for i in range(m) if grid[i][j] == grid[i][0])
        ones = max(ones, m - ones)
        total += ones * (1 << (n - 1 - j))
    return total
function matrixScore(grid) {
  const m = grid.length, n = grid[0].length;
  let total = m * (1 << (n - 1));
  for (let j = 1; j < n; j++) {
    let ones = 0;
    for (let i = 0; i < m; i++) if (grid[i][j] === grid[i][0]) ones++;
    ones = Math.max(ones, m - ones);
    total += ones * (1 << (n - 1 - j));
  }
  return total;
}
class Solution {
    public int matrixScore(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        int total = m * (1 << (n - 1));
        for (int j = 1; j < n; j++) {
            int ones = 0;
            for (int i = 0; i < m; i++) if (grid[i][j] == grid[i][0]) ones++;
            ones = Math.max(ones, m - ones);
            total += ones * (1 << (n - 1 - j));
        }
        return total;
    }
}
int matrixScore(vector<vector<int>>& grid) {
    int m = (int)grid.size(), n = (int)grid[0].size();
    int total = m * (1 << (n - 1));
    for (int j = 1; j < n; j++) {
        int ones = 0;
        for (int i = 0; i < m; i++) if (grid[i][j] == grid[i][0]) ones++;
        ones = max(ones, m - ones);
        total += ones * (1 << (n - 1 - j));
    }
    return total;
}
Time: O(m · n) Space: O(1)