# Score After Flipping Matrix in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

Suppose we have a two dimensional matrix A where each value is 0 or 1. Here a move consists of choosing any row or column, and toggling each value in that row or column: changing all 0s to 1s, and all 1s to 0s. Now after making any number of moves, every row of this matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. So our task is to find the highest possible score. If the input is like −

 0 0 1 1 1 0 1 0 1 1 0 0

The output will be 39 as after toggling, the matrix will be −

 1 1 1 1 1 0 0 1 1 1 1 1

So the numbers are 15 + 9 + 15 = 39

To solve this, we will follow these steps −

• n := row count and m := column count

• ret := n x (2^(m – 1))

• for j in range 1 to m – 1

• cnt : = 0

• for i in range 0 to n – 1

• cnt := cnt + A[i, j] = A[i, 0]

• temp := 2^(m – j – 1) * maximum of cnt and n – cnt

• ret := ret + temp

• return ret

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int matrixScore(vector<vector<int>>& A) {
int n = A.size();
int m = A[0].size();
int ret = (1 << (m - 1)) * n;
for(int j = 1; j < m; j++){
int cnt = 0;
for(int i = 0; i < n; i++){
cnt += (A[i][j] == A[i][0]);
}
int temp = ((1 << (m - (j + 1))) * max(cnt, n - cnt));
ret += temp;
}
return ret;
}
};
main(){
vector<vector<int>> v = {{0,0,1,1},{1,0,1,0},{1,1,0,0}};
Solution ob;
cout << (ob.matrixScore(v));
}

### Input

[[0,0,1,1],[1,0,1,0],[1,1,0,0]]

## Output

39
Updated on 30-Apr-2020 10:22:45