861. Score After Flipping Matrix #194
-
Topics: You are given an A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. Return the highest possible score after making any number of moves (including zero moves). Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to maximize the matrix score by flipping rows or columns. The goal is to interpret each row as a binary number and get the highest possible sum from all the rows. Approach:
Let's implement this solution in PHP: 861. Score After Flipping Matrix <?php
/**
* @param Integer[][] $grid
* @return Integer
*/
function matrixScore($grid) {
$m = count($grid); // Number of rows
$n = count($grid[0]); // Number of columns
// Step 1: Ensure all rows start with 1 by flipping rows if necessary
for ($i = 0; $i < $m; $i++) {
if ($grid[$i][0] == 0) {
// Flip the entire row
for ($j = 0; $j < $n; $j++) {
$grid[$i][$j] = 1 - $grid[$i][$j];
}
}
}
// Step 2: Maximize the number of 1's in each column from the second column onwards
for ($j = 1; $j < $n; $j++) {
$onesCount = 0;
for ($i = 0; $i < $m; $i++) {
if ($grid[$i][$j] == 1) {
$onesCount++;
}
}
// If there are more 0's than 1's in this column, flip the column
if ($onesCount < $m / 2) {
for ($i = 0; $i < $m; $i++) {
$grid[$i][$j] = 1 - $grid[$i][$j];
}
}
}
// Step 3: Calculate the final score by interpreting each row as a binary number
$score = 0;
for ($i = 0; $i < $m; $i++) {
$rowValue = 0;
for ($j = 0; $j < $n; $j++) {
$rowValue = $rowValue * 2 + $grid[$i][$j];
}
$score += $rowValue;
}
return $score;
}
// Test cases
echo matrixScore([[0,0,1,1],[1,0,1,0],[1,1,0,0]]); // Output: 39
echo "\n";
echo matrixScore([[0]]); // Output: 1
?> Explanation:
Time Complexity:
Thus, the total time complexity is Example Walkthrough:For the input: $grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]];
This gives the correct output of |
Beta Was this translation helpful? Give feedback.
We need to maximize the matrix score by flipping rows or columns. The goal is to interpret each row as a binary number and get the highest possible sum from all the rows.
Approach:
Initial Observation:
1
. This means we should first flip any row that starts with a0
.1
, we need to maximize the remaining bits of each row. This can be done by flipping columns to have as many1
s as possible, especially for higher-bit positions.Steps:
1
to ensure the leftmost bit of every row is1
.