Leetcode 861. Score After Flipping Matrix
You are given a matrix consisting of 0s and 1s, and you can perform any number of the following operations:
After each operation, every element of the matrix must still be either 0 or 1. You want to maximize the score after any number of operations. The score is obtained by interpreting each row of the matrix as a binary number, and then summing these numbers.
Your task is to return the maximum possible score.
To maximize the score:
Here’s the implementation of the strategy:
public class Solution {
public int matrixScore(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
// Step 1: Ensure all rows have a leading 1 by flipping rows if necessary.
for (int i = 0; i < rows; i++) {
if (grid[i][0] == 0) {
flipRow(grid, i);
}
}
// Step 2: Optimize each column to maximize the number of 1s.
for (int j = 1; j < cols; j++) {
int numOnes = 0;
// Count the number of 1s in the current column
for (int i = 0; i < rows; i++) {
if (grid[i][j] == 1) {
numOnes++;
}
}
// If more than half of the column elements are 0s, flip the column
if (numOnes < (rows + 1) / 2) {
flipColumn(grid, j);
}
}
// Step 3: Calculate the final score
int score = 0;
for (int i = 0; i < rows; i++) {
int rowValue = 0;
for (int j = 0; j < cols; j++) {
rowValue = rowValue * 2 + grid[i][j];
}
score += rowValue;
}
return score;
}
private void flipRow(int[][] grid, int row) {
for (int j = 0; j < grid[0].length; j++) {
grid[row][j] ^= 1;
}
}
private void flipColumn(int[][] grid, int col) {
for (int i = 0; i < grid.length; i++) {
grid[i][col] ^= 1;
}
}
}
Overall, the time complexity is O(N * M), which is efficient for typical input sizes expected in competitive programming.
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?