The Indian Engineer

Problem 861 Score After Flipping Matrix

Posted on 3 mins

Matrix Greedy Bit-Manipulation Cpp

Problem Statement

Link - Problem 861

Question

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

Example 1

Input: grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation: 0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39

Example 2

Input: grid = [[0]]
Output: 1

Constraints

Solution

class Solution {
public:
    int matrixScore(vector<vector<int>>& grid) {

        std::ios::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);

        for(int row =0; row<grid.size(); row++)
        {
            if(grid[row][0] == 0)
            {
                for(int col = 0; col<grid[0].size(); col++)
                {
                    grid[row][col] = !grid[row][col];
                }
            }
        }

        int zero = 0, one = 0;

        for(int col=0; col<grid[0].size(); col++)
        {
            for(int row=0; row<grid.size(); row++)
            {
                if(grid[row][col] == 0)
                    zero++;
                else
                    one++;
            }
 vector<int>zeroCnt(grid[0].size(),0);
        vector<int>oneCnt(grid[0].size(),0);
            if(zero > one )
            {
                for(int row=0; row<grid.size(); row++)
                {
                    grid[row][col] = !grid[row][col];
                }
            }
            one = 0;
            zero = 0;
        }

        int answer = 0;
        int temp,base;
         for(int row = 0; row<grid.size(); row++)
         {
            temp = 0;
            base = 0;
            for(int col = grid[0].size()-1;  col>=0; col--)
            {
                if(grid[row][col])
                {
                    temp+= (int)pow(2,base);
                }
                base++;
            }
            answer+= temp;
         }
         return answer;


    }
};

Complexity Analysis

Explanation

1. Intuition

2. Implementation


Shows the implementation of greedy technique to maximize the sum of the binary numbers formed by the rows of the matrix.