Given a 2D array, find the maximum sum subarray in it. For example, in the following 2D array, the maximum sum subarray is highlighted with blue rectangle and sum of this subarray is 29.
This problem is mainly an extension of Largest Sum Contiguous Subarray for 1D array.
The naive solution for this problem is to check every possible rectangle in given 2D array. This solution requires 4 nested loops and time complexity of this solution would be O(n^4).
Kadane’s algorithm for 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 maximum sum contiguous rows for every left and right column pair. We basically find top and bottom row numbers (which have maximum sum) for every fixed left and right column pair.
To find the top and bottom row numbers, calculate sum of elements in every row from left to right and store these sums in an array say temp. So temp[i] indicates sum of elements from left to right in row i. If we apply Kadane’s 1D algorithm on temp, and get the maximum sum subarray of temp, this maximum sum would be the maximum possible sum with left and right as boundary columns. To get the overall maximum sum, we compare this sum with the maximum sum so far.
Java implementation for Maximum sum rectangle in a 2D matrix:
Max sum is: 29, range: [(1,1)(3,3]
Time Complexity: O(n^3)