-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path861_flipingmat.cpp
79 lines (61 loc) · 1.63 KB
/
861_flipingmat.cpp
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Solution {
public:
int matrixScore(vector<vector<int>>& grid) {
int m = grid.size();
int 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-grid[i][j];
}
}
}
for(int j=1;j<n;j++){
int cz=0;
for(int i=0;i<m;i++){
if(grid[i][j] == 0){
cz++;
}
}
int c1 = m-cz;
if(c1 < cz){
for(int i=0;i<m;i++){
grid[i][j] = 1-grid[i][j];
}
}
}
int score = 0;
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
int value = grid[i][j] * pow(2,n-j-1);
score += value;
}
}
return score;
}
};
//Approach-2 (Without Modifying the input)
//T.C : O(m*n)
//S.C : O(1)
class Solution {
public:
int matrixScore(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
//MSB -> 2^n-1
int score = pow(2, n-1) * m;
for(int j = 1; j < n; j++) {
int countSameBits = 0; //count of 1s
for(int i = 0; i < m; i++) {
if(grid[i][j] == grid[i][0]) {
countSameBits++;
}
}
int countOnes = countSameBits;
int countZeros = m - countOnes;
int ones = max(countOnes, countZeros);
score += (pow(2, n-j-1) * ones);
}
return score;
}
};