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