Given an N × N matrix of integers, find the maximum sum submatrix present in it.

For example, the maximum sum submatrix is highlighted in green in the following matrices:

 
Maximum Sum Submatrix    Maximum sum matrix    Maximum Sum Submatrix

Practice this problem

 
The idea is to preprocess the matrix. We take an auxiliary matrix S[][], where S[i][j] will store the sum of elements in the matrix from (0, 0) to (i-1, j-1). The idea is similar to the following post:

Calculate the sum of all elements in a submatrix in constant time

 
After we have preprocessed the matrix to create the sum matrix, consider every submatrix formed by row i to j and column m to n to calculate the submatrix sum in constant time using the following relation:

submatrix sum = S[j+1][n+1] – S[j+1][m] – S[i][n+1] + S[i][m]

If the submatrix sum is more than the maximum found so far, we update the maximum sum. We can also store the submatrix coordinates to print the maximum sum submatrix. The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
The maximum sum submatrix is [[7, 8, 3], [-2, -1, 2], [5, 5, 2], [2, 9, -5]]
The maximum sum is 35

The time complexity of the proposed solution is O(N4) for an N × N matrix. The auxiliary space required by the program is O(N2). We can solve this problem in O(N3) time using Kadane’s algorithm.