Open In App

Minimum sum submatrix in a given 2D array

Last Updated : 20 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D array, find the minimum sum submatrix in it.

Examples:  

Input : M[][] = {{1, 2, -1, -4, -20},
                 {-8, -3, 4, 2, 1},
                 {3, 8, 10, 1, 3},
                 {-4, -1, 1, 7, -6}}
Output : -26
Submatrix starting from (Top, Left): (0, 0)
and ending at (Bottom, Right): (1, 4) indexes.
The elements are of the submatrix are:
{ {1, 2, -1, -4, -20},
  {-8, -3, 4, 2, 1}  } having sum = -26

Method 1 (Naive Approach): Check every possible submatrix in a given 2D array. This solution requires 4 nested loops and the time complexity of this solution would be O(n^4).

Method 2 (Efficient Approach): 

Kadane’s algorithm for the 1D array can be used to reduce the time complexity to O(n^3). The idea is to fix the left and right columns one by one and find the minimum sum contiguous rows for every left and right column pair. We basically find top and bottom row numbers (which have minimum sum) for every fixed left and right column pair. To find the top and bottom row numbers, calculate the sum of elements in every row from left to right and store these sums in an array say temp[]. So temp[i] indicates the sum of elements from left to right in row i. 

If we apply Kadane’s 1D algorithm on temp[] and get the minimum sum subarray of temp, this minimum sum would be the minimum possible sum with left and right as boundary columns. To get the overall minimum sum, we compare this sum with the minimum sum so far.

Implementation:

C++





Java





Python3





C#





Javascript





Output

(Top, Left): (0, 0)
(Bottom, Right): (1, 4)
Minimum sum: -26

Time Complexity: O(n3)
Auxiliary Space: O(ROW) 

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads