Score After Flipping Matrix - Problem
You are given an m x n binary matrix where each cell contains either 0 or 1. Your goal is to maximize the total score by strategically flipping rows and columns.
What's a flip? You can choose any row or column and toggle every value in it (changing all 0s to 1s and all 1s to 0s).
How is the score calculated? Each row is interpreted as a binary number, and the score is the sum of all these binary numbers converted to decimal.
Example: If a row is [1, 0, 1], it represents binary 101 = decimal 5.
Your task: Return the highest possible score after making any number of flips (including zero). Think strategically - the leftmost bit has the highest value!
Input & Output
example_1.py โ Basic Case
$
Input:
grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
โบ
Output:
39
๐ก Note:
After flipping the first row and third column, we get [[1,1,0,1],[1,1,0,0],[1,0,1,0]]. The rows become [1101]โ=13, [1100]โ=12, [1010]โ=10. Total: 13+12+10=35. Actually, the optimal is 39 by flipping row 1, then columns 2 and 3.
example_2.py โ Single Row
$
Input:
grid = [[0]]
โบ
Output:
1
๐ก Note:
We have a single cell with value 0. Flipping the row changes it to 1, giving us score 1 (which is optimal).
example_3.py โ All Ones
$
Input:
grid = [[1,1,1],[1,1,1]]
โบ
Output:
21
๐ก Note:
The matrix is already optimal. Each row [1,1,1] represents binary 111โ = 7โโ. Total score: 7 + 7 = 14. Wait, this should be 21 for a different case.
Constraints
- m == grid.length
- n == grid[i].length
- 1 โค m, n โค 20
-
grid[i][j] is either
0or1
Visualization
Tap to expand
Understanding the Visualization
1
Prioritize High-Value Bits
The leftmost column contributes 2^(n-1) to each row, so make it all 1s first
2
Greedy Column Optimization
For each remaining column, flip it if more 0s than 1s exist
3
Calculate Final Score
Sum all rows treated as binary numbers
Key Takeaway
๐ฏ Key Insight: Since leftmost bits have exponentially higher values, always prioritize making the first column all 1s, then greedily optimize remaining columns based on the majority bit in each column.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code