Maximum sum submatrix | Function to find maximum sum submatrix ; Stores the number of rows and columns in the matrix ; Stores maximum submatrix sum ; Take each row as starting row ; Take each column as the starting column ; Take each row as the ending row ; Take each column as the ending column ; Stores the sum of submatrix having topleft index ( i , j ) and bottom right index ( k , l ) ; Iterate the submatrix row - wise and calculate its sum ; Update the maximum sum ; Print the answer ; Driver Code
function maxSubmatrixSum ( matrix ) { var r = matrix . length ; var c = matrix [ 0 ] . length ; var maxSubmatrix = 0 ; for ( i = 0 ; i < r ; i ++ ) { for ( j = 0 ; j < c ; j ++ ) { for ( k = i ; k < r ; k ++ ) { for ( l = j ; l < c ; l ++ ) { var sumSubmatrix = 0 ; for ( m = i ; m <= k ; m ++ ) { for ( n = j ; n <= l ; n ++ ) { sumSubmatrix += matrix [ m ] [ n ] ; } } maxSubmatrix = Math . max ( maxSubmatrix , sumSubmatrix ) ; } } } } document . write ( maxSubmatrix ) ; } var matrix = [ [ 0 , - 2 , - 7 , 0 ] , [ 9 , 2 , - 6 , 2 ] , [ - 4 , 1 , - 4 , 1 ] , [ - 1 , 8 , 0 , - 2 ] ] ; maxSubmatrixSum ( matrix ) ;