Score After Flipping Matrix - Problem

You are given an m x n binary matrix grid. A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all 0's to 1's, and all 1's to 0's).

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).

Input & Output

Example 1 — Basic Matrix
$ Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
💡 Note: After optimal flips: flip row 0 to get [[1,1,0,0],[1,0,1,0],[1,1,0,0]], then flip column 1 to get [[1,0,0,0],[1,1,1,0],[1,0,0,0]]. Final score: 8+14+8=30. Actually, better solution gives 39.
Example 2 — Single Row
$ Input: grid = [[0]]
Output: 1
💡 Note: Single cell matrix. Flip the row to change 0 to 1. Score becomes 1.
Example 3 — Already Optimal
$ Input: grid = [[1,1,1],[1,1,1]]
Output: 14
💡 Note: Matrix is already optimal. Each row has value 7 (111 in binary), so total score is 7+7=14.

Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 ≤ m, n ≤ 20
  • grid[i][j] is either 0 or 1

Visualization

Tap to expand
Score After Flipping MatrixInput Matrix:00111010= 3= 5Initial Score: 3 + 5 = 8After Optimal Flips:11111111= 15= 15Maximum Score: 15 + 15 = 30Goal: Flip rows/columns to maximize total scoreEach row is a binary number - leftmost bits contribute most!
Understanding the Visualization
1
Input Matrix
Binary matrix where each row represents a binary number
2
Apply Flips
Strategically flip rows and columns to maximize score
3
Calculate Score
Sum the binary values of all rows
Key Takeaway
🎯 Key Insight: Prioritize leftmost columns first since they contribute exponentially more to the final score
Asked in
Google 12 Amazon 8 Microsoft 6
89.5K 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