File tree Expand file tree Collapse file tree 1 file changed +62
-0
lines changed
Expand file tree Collapse file tree 1 file changed +62
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Greedy
3+ * Time O(n) | Space O(1)
4+ * https://leetcode.com/problems/score-after-flipping-matrix
5+ * @param {number[][] } grid
6+ * @return {number }
7+ */
8+ var matrixScore = function ( grid ) {
9+
10+ const ROW = grid [ 0 ] . length ;
11+ const COL = grid . length ;
12+
13+ const countZeros = ( col ) => {
14+
15+ let start = 0 ;
16+ let count = 0 ;
17+ while ( start < COL ) {
18+ if ( ! grid [ start ] [ col ] ) count ++ ; ;
19+ start ++ ;
20+ }
21+
22+ return count ;
23+ }
24+
25+ const flip = ( i , isRow ) => {
26+ let start = 0 ;
27+
28+ if ( isRow ) {
29+ while ( start < ROW ) {
30+ grid [ i ] [ start ] ^= 1 ;
31+ start ++ ;
32+ }
33+ return ;
34+ }
35+
36+ if ( ! isRow ) {
37+ while ( start < COL ) {
38+ grid [ start ] [ i ] ^= 1 ;
39+ start ++ ;
40+ }
41+ return ;
42+ }
43+ }
44+
45+ for ( let i = 0 ; i < COL ; i ++ ) {
46+ if ( ! grid [ i ] [ 0 ] ) flip ( i , true ) ;
47+
48+ for ( let j = ( grid [ i ] [ 0 ] && 1 ) ; j < ROW ; j ++ ) {
49+ const numberOfZeros = countZeros ( j ) ;
50+ if ( numberOfZeros > COL - numberOfZeros ) {
51+ flip ( j , false ) ;
52+ }
53+ }
54+ }
55+
56+ let total = 0 ;
57+ for ( let i = 0 ; i < COL ; i ++ ) {
58+ total += parseInt ( grid [ i ] . join ( "" ) , 2 ) ;
59+ }
60+
61+ return total ;
62+ } ;
You can’t perform that action at this time.
0 commit comments