The Maximum Sum Rectangle problem is a classic problem in computer science where we have to find the sub-matrix with the maximum sum in a given 2D array. We can solve this problem using dynamic programming using an approach known as Kadane’s algorithm.
Kadane’s algorithm is used to solve the maximum sub-array problem in a 1D array. However, it can be extended to solve the maximum sub-matrix problem in a 2D array with a little modification.
The algorithm involves iterating over the 2D array row by row and keeping track of the maximum sum so far. For each row, we maintain a 1D array containing the sum of elements in the current row and all the previous rows up to the first row.
To compute the maximum sum rectangle, we will use two nested loops for the starting and ending row of the sub-matrix and keep track of the sum of elements in the sub-matrix. We then use Kadane’s algorithm to find the maximum sum of elements in that sub-matrix and update the maximum sum found so far.
Here is the implementation of the dynamic programming solution to the Maximum Sum Rectangle problem in Java:
public static int maxSumRectangle(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i < rows; i++) {
int[] rowSum = new int[cols];
// Add sum of all the rows above the current row
for (int k = i; k < rows; k++) {
int sum = 0;
for (int j = 0; j < cols; j++) {
rowSum[j] += matrix[k][j];
sum += rowSum[j];
maxSum = Math.max(maxSum, sum);
// Use Kadane's algorithm to find the maximum sum of elements in the sub-matrix
sum = Math.max(0, sum);
}
}
}
return maxSum;
}
In the above implementation, we first loop through all the rows of the matrix and maintain a 1D array ‘rowSum‘ which contains the cumulative sum of elements in the 2D array up to the current row.
Then, we use two nested loops to consider all possible sub-matrices of the matrix and compute their sum. For each sub-matrix, we pass the ‘rowSum‘ array to the Kadane’s algorithm function, which returns the maximum sum of elements in the sub-matrix.
We keep track of the maximum sum found so far and return it once all the sub-matrices have been considered.
The time complexity of the above algorithm is O(n3), where n is the number of elements in the 2D array. However, it can be improved to O(n2 by using the optimized Kadane’s algorithm for 1D arrays.