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 code ; function call to print required answer
using System ; using System . Collections . Generic ; class GFG { static int n = 3 ; static int m = 4 ; static int maxMatrixScore ( int [ , ] A , int K ) { Dictionary < int , int > update = new Dictionary < int , int > ( ) ; int ans = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( A [ i , 0 ] == 0 ) { ans = 0 ; for ( int j = 1 ; j < m ; ++ j ) ans = ( int ) ( ans + A [ i , j ] * Math . Pow ( 2 , m - j - 1 ) ) ; update . Add ( ( int ) ans , i ) ; } } foreach ( KeyValuePair < int , int > it in update ) if ( K > 0 ) { int idx = it . Value ; for ( int j = 0 ; j < m ; ++ j ) A [ idx , j ] = ( A [ idx , j ] + 1 ) % 2 ; K -- ; } ans = 0 ; for ( int j = 0 ; j < m ; ++ j ) { int zero = 0 , one = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( A [ i , j ] == 0 ) zero ++ ; else one ++ ; } if ( K > 0 && zero > one ) { ans += zero * ( int ) Math . Pow ( 2 , m - j - 1 ) ; K -- ; } else ans += one * ( int ) Math . Pow ( 2 , m - j - 1 ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ , ] A = { { 0 , 0 , 1 , 1 } , { 1 , 0 , 1 , 0 } , { 1 , 1 , 0 , 0 } } ; int K = 2 ; Console . Write ( maxMatrixScore ( A , K ) ) ; } }