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 Matrix INPUT Binary Matrix (3x4) 0 0 1 1 1 0 1 0 1 1 0 0 col0 col1 col2 col3 Initial Binary Values: Row0: 0011 = 3 Row1: 1010 = 10 Row2: 1100 = 12 Initial Sum = 25 ALGORITHM STEPS 1 Flip rows for col0=1 MSB must be 1 for max value Flip Row0: 0011 --> 1100 2 Optimize col1 Count 1s: 2/3, keep as is More 1s than 0s = no flip 3 Optimize col2 Count 1s: 1/3, flip column Flip col2: 0,1,0 --> 1,0,1 4 Optimize col3 Count 1s: 1/3, flip column Flip col3: 0,0,0 --> 1,1,1 After Optimization: [1,1,1,1] [1,0,0,1] [1,1,1,1] Each row starts with 1 FINAL RESULT Optimized Matrix 1 1 1 1 = 15 1 0 0 1 = 9 1 1 1 1 = 15 Score Calculation: 1111 = 8+4+2+1 = 15 1001 = 8+0+0+1 = 9 Maximum Score 39 OK Key Insight: Greedy Column-by-Column Optimization 1. First, ensure all rows start with 1 (MSB) by flipping rows where grid[i][0] = 0. This maximizes the leftmost bit contribution. 2. Then, for each remaining column, flip it if more than half the values are 0. Each column contributes 2^(n-1-col) per 1-bit. 3. Time: O(m*n), Space: O(1). Row flips and column flips are independent operations after fixing the first column. TutorialsPoint - Score After Flipping Matrix | Greedy Column-by-Column Approach
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