Consider a matrix M with integer values. We seek to find a rectangular subarray of M whose sum of elements is maximized.
First, let’s examine the 1D version of the problem. The brute force approach would be as we would have to examine all subarrays of M and build up the sums incrementally. A cleverer way is by using Dynamic Programming in Kadane’s algorithm.
Let denote the maximum sum subarray of M ending at index . We can easily see how the following recursive formula holds:
After finding for all i, we can loop through those values to get the maximum one. The time complexity is .
For the 2D version of the problem, we employ a small trick. We examine the space between all possible pairs of columns. Let and be two columns of M. Then we want to constructively construct an array T such that T[i] holds the sum of all values of row i of M between the two columns. On T we run Kadane’s algorithm for 1D to get our solution. This algorithm runs in over the brute force approach.