Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Flipped Matrix Prequel in C++
Suppose we have one binary matrix. We have to find the maximum number of 1s we can get if we flip a row and then flip a column.
So, if the input is like
| 1 | 0 | 1 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
then the output will be 8
To solve this, we will follow these steps −
n := size of rows in matrix
m := size of columns in matrix
ret := 0
Define an array row of size n
Define an array col of size n
total := 0
-
for initialize i := 0, when i < n, update (increase i by 1), do −
-
for initialize j := 0, when j < m, update (increase j by 1), do −
row[i] := row[i] + matrix[i, j]
col[j] := col[j] + matrix[i, j]
total := total + matrix[i, j]
-
-
for initialize i := 0, when i < n, update (increase i by 1), do −
-
for initialize j := 0, when j < m, update (increase j by 1), do −
cand := total - row[i] - col[j] + ((m - row[i]) + (n - col[j]))
-
if matrix[i, j] is non-zero, then −
cand := cand + 2
-
Otherwise
cand := cand - 2
ret := maximum of ret and cand
-
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(vector<vector<int>> &matrix) {
int n = matrix.size();
int m = matrix[0].size();
int ret = 0;
vector<int> row(n);
vector<int> col(m);
int total = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
row[i] += matrix[i][j];
col[j] += matrix[i][j];
total += matrix[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int cand = total - row[i] - col[j] + (m - row[i]) + (n -
col[j]);
if (matrix[i][j]) {
cand += 2;
}else {
cand -= 2;
}
ret = max(ret, cand);
}
}
return ret;
}
};
main() {
Solution ob;
vector<vector<int>> v = {{1,0,1},{0,1,0},{1,0,0}};
cout << (ob.solve(v));
}
Input
{{1,0,1},{0,1,0},{1,0,0}}
Output
8