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 0 or 1

Visualization

Tap to expand
Matrix Score Optimization: Bit Value HierarchyBinary Place Values (4-bit example)82ยณ42ยฒ22ยน12โฐStrategy: Optimize columns from left to rightColumn 1 impact > Column 2 impact > Column 3 impact > Column 4 impactAlways make first column all 1s (flip rows if needed)!Greedy Algorithm StepsStep 1Flip rows to makefirst column all 1sStep 2For each column j,flip if more 0s than 1sStep 3Calculate score:ฮฃ(binary to decimal)
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.
Asked in
Google 42 Amazon 28 Microsoft 19 Meta 15
52.3K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen