Given an M × N integer matrix, calculate the maximum sum submatrix of size k × k in it in O(M × N) time. Here, 0 < k < M <= N.

For example, consider the following 5 × 5 matrix:

 
[  3 -4  6 -5  1 ]
[  1 -2  8 -4 -2 ]
[  3 -8  9  3  1 ]
[ -7  3  4  2  7 ]
[ -3  7 -5  7 -6 ]
 
 
If k = 2, the maximum sum k × k submatrix is
 
[ 9 3 ]
[ 4 2 ]
 
 
If k = 3, the maximum sum k × k submatrix is
 
[ 8 -4 -2 ]
[ 9  3  1 ]
[ 4  2  7 ]

Practice this problem

We strongly suggest going through the following post as a prerequisite of the below solution:

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

 
The idea is to preprocess the matrix. We take an auxiliary matrix sum[][], where sum[i][j] stores the sum of elements in the matrix from (0, 0) to (i, j). We can easily calculate the value of sum[i][j] in constant time using the following relation:

sum[i][j] = sum[i][j – 1] + sum[i – 1][j] + mat[i][j] – sum[i – 1][j – 1]

Now to find the maximum sum k × k submatrix, consider every submatrix of size k × k and calculate their sum in constant time by directly using the following relation:

submatrixSum = sum[i][j] – sum[i – k][j] – sum[i][j – k] + sum[i – k][j – k]

Here, (i, j) represents the bottom-right corner coordinates of the k × k submatrix. Finally, print the submatrix that has the maximum sum.

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:
 
[8, -4, -2]
[9, 3, 1]
[4, 2, 7]

The time complexity of the proposed solution is O(M × N) and requires O(M × N) extra space, where M and N are dimensions of the matrix.