# Maximum score after flipping a Binary Matrix atmost K times

Given a two dimensional matrix A of zero’s and one’s and an integer K.

In each move, you can choose any row or column and toggle every value in that row or column. That is, change all 0s to 1s, or all 1s to 0s. After making atmost K of moves, every row of this matrix represents a binary number.

The task is to return the maximum possible value of the sum of these numbers.

Examples:

Input : A[][] = { { 0, 0, 1, 1 },
{ 1, 0, 1, 0 },
{ 1, 1, 0, 0 } };
K = 2
Output : 36

Input : A[][] = { { 0, 1 },
{ 1, 0 },
{ 1, 1 } };
K = 1
Output : 7


## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Notice that a 1 in the i-th column from the right, contributes 2i to the score.

Also knowing the fact that, , maximizing the left-most digit is more important than any other digit. Thus, any rows should be toggled such that the left most column should be either all 0 or all 1 (so that after toggling the left-most column [if necessary], the left column is all 1).

Now for rows with first element as 0, make a map with value of row as key and index of that row as element. Now we toggle rows with least value so that after updating it contributes maximum to our total score.

Now, for other subsequent columns we count total zeros and ones.

• If ( zeros > ones and K > 0 ) we toggle the column and update our answer to ans = ans + zero * pow( 2, columns – j – 1), for all and decrements K by one.
• Otherwise we update answer to ans = ans + one * pow( 2, columns – j – 1), for all .

Below is the implementation of above approach:

## C++

 // C++ program to find the maximum score after  // flipping a Binary Matrix atmost K times  #include  using namespace std;     const int n = 3;  const int m = 4;     // Function to find maximum score of matrix  int maxMatrixScore(int A[n][m], int K)  {      map<int, int> update;         // find value of rows having first      // column value equal to zero      for (int i = 0; i < n; ++i) {          if (A[i] == 0) {              int ans = 0;                 for (int j = 1; j < m; ++j)                  ans = ans + A[i][j] * pow(2, m - j - 1);                 update[ans] = i;          }      }         // update those rows which lead to      // maximum score after toggle      map<int, int>::iterator it = update.begin();         while (K > 0 && it != update.end()) {             int idx = it->second;             for (int j = 0; j < m; ++j)              A[idx][j] = (A[idx][j] + 1) % 2;             it++;          K--;      }         // Calculating answer      int ans = 0;         for (int j = 0; j < m; ++j) {             int zero = 0, one = 0;             for (int i = 0; i < n; ++i) {              A[i][j] == 0 ? zero++ : one++;          }             // check if K > 0 we can toggle if necessary.          if (K > 0 && zero > one) {              ans += zero * pow(2, m - j - 1);              K--;          }          else             ans += one * pow(2, m - j - 1);      }         // return max answer possible      return ans;  }     // Driver program  int main()  {      int A[n][m] = { { 0, 0, 1, 1 },                      { 1, 0, 1, 0 },                      { 1, 1, 0, 0 } };      int K = 2;      // function call to print required answer      cout << maxMatrixScore(A, K);         return 0;  }

## Python3

 # Python3 program to find the maximum   # score after flipping a Binary Matrix  # atmost K times      n = 3 m = 4    # Function to find maximum score of matrix   def maxMatrixScore(A, K):          update = {}         # Find value of rows having first       # column value equal to zero       for i in range(0, n):           if A[i] == 0:                             ans = 0             for j in range(1, m):                   ans = ans + A[i][j] * 2 ** (m - j - 1)                  update[ans] = i                  # update those rows which lead to       # maximum score after toggle       for idx in update.values():              for j in range(0, m):               A[idx][j] = (A[idx][j] + 1) % 2            K -= 1         if K <= 0:              break        # Calculating answer       ans = 0     for j in range(0, m):                      zero, one = 0, 0            for i in range(0, n):               if A[i][j] == 0: zero += 1             else: one += 1            # check if K > 0 we can           # toggle if necessary.           if K > 0 and zero > one:               ans += zero * 2 ** (m - j - 1)               K -= 1                    else:              ans += one * 2 ** (m - j - 1)              # return max answer possible       return ans      # Driver Code  if __name__ == "__main__":          A = [[0, 0, 1, 1],            [1, 0, 1, 0],            [1, 1, 0, 0]]              K = 2            # function call to print required answer       print(maxMatrixScore(A, K))      # This code is contributed by Rituraj Jain

Output:

36


Time Complexity: O(N*M)

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : rituraj_jain

Article Tags :
Practice Tags :

2

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.