Minimum operations required to make each row and column of matrix equals | Function to find minimum operation required to make sum of each row and column equals ; Initialize the sumRow [ ] and sumCol [ ] array to 0 ; Calculate sumRow [ ] and sumCol [ ] array ; Find maximum sum value in either row or in column ; Find minimum increment required in either row or column ; Add difference in corresponding cell , sumRow [ ] and sumCol [ ] array ; Update the count variable ; If ith row satisfied , increment ith value for next iteration ; If jth column satisfied , increment jth value for next iteration ; Utility function to print matrix ; Driver program
function findMinOpeartion ( matrix , n ) { let sumRow = new Array ( n ) ; let sumCol = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) { sumRow [ i ] = 0 ; sumCol [ i ] = 0 ; } for ( let i = 0 ; i < n ; ++ i ) for ( let j = 0 ; j < n ; ++ j ) { sumRow [ i ] += matrix [ i ] [ j ] ; sumCol [ j ] += matrix [ i ] [ j ] ; } let maxSum = 0 ; for ( let i = 0 ; i < n ; ++ i ) { maxSum = Math . max ( maxSum , sumRow [ i ] ) ; maxSum = Math . max ( maxSum , sumCol [ i ] ) ; } let count = 0 ; for ( let i = 0 , j = 0 ; i < n && j < n ; ) { let diff = Math . min ( maxSum - sumRow [ i ] , maxSum - sumCol [ j ] ) ; matrix [ i ] [ j ] += diff ; sumRow [ i ] += diff ; sumCol [ j ] += diff ; count += diff ; if ( sumRow [ i ] == maxSum ) ++ i ; if ( sumCol [ j ] == maxSum ) ++ j ; } return count ; } function printMatrix ( matrix , n ) { for ( let i = 0 ; i < n ; ++ i ) { for ( let j = 0 ; j < n ; ++ j ) document . write ( matrix [ i ] [ j ] + " " ) ; document . write ( " " ) ; } } let matrix = [ [ 1 , 2 ] , [ 3 , 4 ] ] ; document . write ( findMinOpeartion ( matrix , 2 ) + " " ) ; printMatrix ( matrix , 2 ) ;