Skip to content

Commit 7eedaaf

Browse files
committed
Add solution #861
1 parent 7d42e71 commit 7eedaaf

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -668,6 +668,7 @@
668668
858|[Mirror Reflection](./0858-mirror-reflection.js)|Medium|
669669
859|[Buddy Strings](./0859-buddy-strings.js)|Easy|
670670
860|[Lemonade Change](./0860-lemonade-change.js)|Easy|
671+
861|[Score After Flipping Matrix](./0861-score-after-flipping-matrix.js)|Medium|
671672
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
672673
868|[Binary Gap](./0868-binary-gap.js)|Easy|
673674
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 861. Score After Flipping Matrix
3+
* https://leetcode.com/problems/score-after-flipping-matrix/
4+
* Difficulty: Medium
5+
*
6+
* You are given an m x n binary matrix grid.
7+
*
8+
* A move consists of choosing any row or column and toggling each value in that row or
9+
* column (i.e., changing all 0's to 1's, and all 1's to 0's).
10+
*
11+
* Every row of the matrix is interpreted as a binary number, and the score of the matrix
12+
* is the sum of these numbers.
13+
*
14+
* Return the highest possible score after making any number of moves (including zero moves).
15+
*/
16+
17+
/**
18+
* @param {number[][]} grid
19+
* @return {number}
20+
*/
21+
var matrixScore = function(grid) {
22+
const rows = grid.length;
23+
const cols = grid[0].length;
24+
25+
for (let row = 0; row < rows; row++) {
26+
if (grid[row][0] === 0) {
27+
for (let col = 0; col < cols; col++) {
28+
grid[row][col] ^= 1;
29+
}
30+
}
31+
}
32+
33+
let result = rows * (1 << (cols - 1));
34+
35+
for (let col = 1; col < cols; col++) {
36+
let onesCount = 0;
37+
for (let row = 0; row < rows; row++) {
38+
onesCount += grid[row][col];
39+
}
40+
const maxOnes = Math.max(onesCount, rows - onesCount);
41+
result += maxOnes * (1 << (cols - 1 - col));
42+
}
43+
44+
return result;
45+
};

0 commit comments

Comments
 (0)