Leetcode 861. Score After Flipping Matrix
You are given an m x n
binary matrix grid
. You can perform two types of operations on the matrix:
Your goal is to maximize the sum of the matrix. The value of a matrix is the binary number represented by the row when each row is interpreted as a binary number. Return the highest possible sum of the matrix.
m
and n
are both up to 20 or 100.1
. If the leading bit of any row is 0
, flip that row.0
in that column. If so, flip the entire column to maximize the number of 1
s because flipping the column would lead to a higher number of 1
s, thereby increasing the total sum.#include <vector>
#include <cmath>
class Solution {
public:
int matrixScore(std::vector<std::vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
// Step 1: Ensure the first column has all 1s by flipping rows if needed
for (int i = 0; i < m; i++) {
if (grid[i][0] == 0) {
flipRow(grid, i);
}
}
// Step 2: Maximize the number of 1s in each column from second to n-th
for (int j = 1; j < n; j++) {
int count0 = 0;
for (int i = 0; i < m; i++) {
if (grid[i][j] == 0) {
count0++;
}
}
if (count0 > m / 2) {
flipColumn(grid, j);
}
}
// Step 3: Calculate the final sum
int sum = 0;
for (int i = 0; i < m; i++) {
int row_value = 0;
for (int j = 0; j < n; j++) {
row_value = (row_value << 1) | grid[i][j];
}
sum += row_value;
}
return sum;
}
private:
void flipRow(std::vector<std::vector<int>>& grid, int row) {
for (int j = 0; j < grid[0].size(); j++) {
grid[row][j] ^= 1;
}
}
void flipColumn(std::vector<std::vector<int>>& grid, int col) {
for (int i = 0; i < grid.size(); i++) {
grid[i][col] ^= 1;
}
}
};
Therefore, the overall time complexity is (O(m \times n)), which is efficient for typical input size constraints.
The provided solution ensures that the matrix is manipulated in such a way that the resulting binary sum is maximized by focusing on flipping rows to ensure leading 1s and flipping columns to maximize the number of 1s per column.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?