The Maximum Sum Problem
Recently I have been solving algorithms problems for fun and thought it'd be a good idea to share some of my solutions here. So here's one called the Maxmimum Sum Problem.
Given an matrix of integers, find the sum of sub-rectangular (doesn't have to be a square) matrix with the largest sum.
For example, given this matrix:
The sub-matrix with the largest sum is:
So the solution is the sum of this matrix, which is 8.
NOTE: There are actually three more sub-matrices in this example that sum to 8. Can you find them?
- Compute an matrix of the partial vertical sums of the input matrix. Such that . For our example above, that will give us a matrix that looks like this:
This matrix can be computed in time by adding the new row to the results of the previous row.
- Now we can use the we computed to find all the possible rectangles of width 1 in another matrix by subtracting rows:
Matrices of height 1:
Matrices of height 2:
Matrices of height n-1:
Matrices of height n:
After doing each of these calculations we will have a bunch of resulting rows. In the case of our example we will end up with the following rows:
These rows can all be found in time.
- The numbers in the rows from step 2 represent the sums of all the possible rectangles of width 1. To find the sum of rectangles with other widths, we can sum horizontally. So we are left with a problem of finding the maximum sum consecutive sub-sequence in each row. The greatest of each of these results is the answer to the problem.The maximum sum subarray for each row can be found in time by calculating the maximum sub-array that ends at each position in the row as follows:
The max-sum of the row is now the maximum value in .
For example, the first row would produce a array of . The maximum number in this row is 2.
And the second row would produce a array of . The maximum number in this row is 7.
After we do this for all the rows we are left with .
Since there are rows and the maximum sum within each row can be computed in time, the complexity of this step is .
The maximum of all those values is the maximum sum of the original matrix. In our example, the largest number was 8, suggesting that the sum of the maximum-sum submatrix is 8.
The complexity of all the steps together is then , giving us a total complexity of for the entire algorithm.