Skip to content

Latest commit

 

History

History
162 lines (125 loc) · 3.44 KB

File metadata and controls

162 lines (125 loc) · 3.44 KB

中文文档

Description

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.

Solutions

Python3

class Solution:
    def matrixScore(self, grid: List[List[int]]) -> int:
        m, n = len(grid), len(grid[0])
        for i in range(m):
            if grid[i][0] == 0:
                for j in range(n):
                    grid[i][j] ^= 1

        res = 0
        for j in range(n):
            cnt = 0
            for i in range(m):
                cnt += grid[i][j]
            res += max(cnt, m - cnt) * (1 << (n - j - 1))
        return res

Java

class Solution {
    public int matrixScore(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        for (int i = 0; i < m; ++i) {
            if (grid[i][0] == 0) {
                for (int j = 0; j < n; ++j) {
                    grid[i][j] ^= 1;
                }
            }
        }
        int res = 0;
        for (int j = 0; j < n; ++j) {
            int cnt = 0;
            for (int i = 0; i < m; ++i) {
                cnt += grid[i][j];
            }
            res += Math.max(cnt, m - cnt) * (1 << (n - j - 1));
        }
        return res;
    }
}

C++

class Solution {
public:
    int matrixScore(vector<vector<int>>& grid) {
        int m = grid.size(), n = grid[0].size();
        for (int i = 0; i < m; ++i)
        {
            if (grid[i][0] == 0)
            {
                for (int j = 0; j < n; ++j) grid[i][j] ^= 1;
            }
        }
        int res = 0;
        for (int j = 0; j < n; ++j)
        {
            int cnt = 0;
            for (int i = 0; i < m; ++i) cnt += grid[i][j];
            res += max(cnt, m - cnt) * (1 << (n - j - 1));
        }
        return res;
    }
};

Go

func matrixScore(grid [][]int) int {
	m, n := len(grid), len(grid[0])
	for i := 0; i < m; i++ {
		if grid[i][0] == 0 {
			for j := 0; j < n; j++ {
				grid[i][j] ^= 1
			}
		}
	}
	res := 0
	for j := 0; j < n; j++ {
		cnt := 0
		for i := 0; i < m; i++ {
			cnt += grid[i][j]
		}
		res += max(cnt, m-cnt) * (1 << (n - j - 1))
	}
	return res
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}

...