Maximize sum of diagonal of a matrix by rotating all rows or all columns | Javascript program to implement the above approach ; Function to find maximum sum of diagonal elements of matrix by rotating either rows or columns ; Stores maximum diagonal sum of elements of matrix by rotating rows or columns ; Rotate all the columns by an leteger in the range [ 0 , N - 1 ] ; Stores sum of diagonal elements of the matrix ; Calculate sum of diagonal elements of the matrix ; Update curr ; Update maxDiagonalSum ; Rotate all the rows by an leteger in the range [ 0 , N - 1 ] ; Stores sum of diagonal elements of the matrix ; Calculate sum of diagonal elements of the matrix ; Update curr ; Update maxDiagonalSum ; Driver Code
let N = 3 ; function findMaximumDiagonalSumOMatrixf ( A ) { let maxDiagonalSum = Number . MIN_VALUE ; for ( let i = 0 ; i < N ; i ++ ) { let curr = 0 ; for ( let j = 0 ; j < N ; j ++ ) { curr += A [ j ] [ ( i + j ) % N ] ; } maxDiagonalSum = Math . max ( maxDiagonalSum , curr ) ; } for ( let i = 0 ; i < N ; i ++ ) { let curr = 0 ; for ( let j = 0 ; j < N ; j ++ ) { curr += A [ ( i + j ) % N ] [ j ] ; } maxDiagonalSum = Math . max ( maxDiagonalSum , curr ) ; } return maxDiagonalSum ; } let mat = [ [ 1 , 1 , 2 ] , [ 2 , 1 , 2 ] , [ 1 , 2 , 2 ] ] ; document . write ( findMaximumDiagonalSumOMatrixf ( mat ) ) ;