-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Copy path0861-score-after-flipping-matrix.js
62 lines (51 loc) · 1.26 KB
/
0861-score-after-flipping-matrix.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
* Greedy
* Time O(n) | Space O(1)
* https://leetcode.com/problems/score-after-flipping-matrix
* @param {number[][]} grid
* @return {number}
*/
var matrixScore = function(grid) {
const ROW = grid[0].length;
const COL = grid.length;
const countZeros = (col) => {
let start = 0;
let count = 0;
while (start < COL) {
if (!grid[start][col]) count++;
start++;
}
return count;
}
const flip = (i, isRow) => {
let start = 0;
if (isRow) {
while (start < ROW) {
grid[i][start] ^= 1;
start++;
}
return;
}
if (!isRow) {
while (start < COL) {
grid[start][i] ^= 1;
start++;
}
return;
}
}
for (let i = 0; i < COL; i++) {
if (!grid[i][0]) flip(i, true);
for (let j = (grid[i][0] && 1); j < ROW; j++) {
const numberOfZeros = countZeros(j);
if (numberOfZeros > COL - numberOfZeros) {
flip(j, false);
}
}
}
let total = 0;
for (let i = 0; i < COL; i++) {
total += parseInt(grid[i].join(""), 2);
}
return total;
};