Maximum sum submatrix | Java program for the above approach ; 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
import java . util . * ; class GFG { static void maxSubmatrixSum ( int [ ] [ ] matrix ) { int r = matrix . length ; int c = matrix [ 0 ] . length ; int maxSubmatrix = 0 ; for ( int i = 0 ; i < r ; i ++ ) { for ( int j = 0 ; j < c ; j ++ ) { for ( int k = i ; k < r ; k ++ ) { for ( int l = j ; l < c ; l ++ ) { int sumSubmatrix = 0 ; for ( int m = i ; m <= k ; m ++ ) { for ( int n = j ; n <= l ; n ++ ) { sumSubmatrix += matrix [ m ] [ n ] ; } } maxSubmatrix = Math . max ( maxSubmatrix , sumSubmatrix ) ; } } } } System . out . println ( maxSubmatrix ) ; } public static void main ( String [ ] args ) { int [ ] [ ] matrix = { { 0 , - 2 , - 7 , 0 } , { 9 , 2 , - 6 , 2 } , { - 4 , 1 , - 4 , 1 } , { - 1 , 8 , 0 , - 2 } } ; maxSubmatrixSum ( matrix ) ; } }