Maximum score after flipping a Binary Matrix atmost K times | Javascript 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
var n = 3 ; var m = 4 ; function maxMatrixScore ( A , K ) { var update = new Map ( ) ; for ( var i = 0 ; i < n ; ++ i ) { if ( A [ i ] [ 0 ] == 0 ) { var ans = 0 ; for ( var j = 1 ; j < m ; ++ j ) ans = ans + A [ i ] [ j ] * Math . pow ( 2 , m - j - 1 ) ; update . set ( ans , i ) ; } } update . forEach ( ( value , key ) => { if ( K > 0 ) { var idx = value ; for ( var j = 0 ; j < m ; ++ j ) A [ idx ] [ j ] = ( A [ idx ] [ j ] + 1 ) % 2 ; K -- ; } } ) ; var ans = 0 ; for ( var j = 0 ; j < m ; ++ j ) { var zero = 0 , one = 0 ; for ( var i = 0 ; i < n ; ++ i ) { A [ i ] [ j ] == 0 ? zero ++ : one ++ ; } if ( K > 0 && zero > one ) { ans += zero * Math . pow ( 2 , m - j - 1 ) ; K -- ; } else ans += one * Math . pow ( 2 , m - j - 1 ) ; } return ans ; } var A = [ [ 0 , 0 , 1 , 1 ] , [ 1 , 0 , 1 , 0 ] , [ 1 , 1 , 0 , 0 ] ] ; var K = 2 ; document . write ( maxMatrixScore ( A , K ) ) ;