
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Find zeroes to be flipped so that number of consecutive 1’s is maximized in C++
- Bisymmetric matrix in C++?
- Spiral Matrix in C++
- 01 Matrix in C++
- Program to count number of on lights flipped by n people in Python
- Transpose a matrix in C#
- Matrix Block Sum in C++
- Spiral Matrix III in C++
- Reshape the Matrix in C++
- Random Flip Matrix in C++
- Diagonally Dominant Matrix in C++?
- Sparse Matrix Multiplication in C++
- Program to check diagonal matrix and scalar matrix in C++
- C++ Boolean Matrix
- Program to convert given Matrix to a Diagonal Matrix in C++
