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 0
s to 1
s, and all 1
s to 0
s.
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 <= A.length <= 20
1 <= A[0].length <= 20
A[i][j]
is0
or1
.
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
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;
}
}
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;
}
};
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
}