04. Maximum Sum Rectangle
β GFG solution to the Maximum Sum Rectangle problem: find maximum possible sum of any submatrix using column compression and Kadane's algorithm. π
The problem can be found at the following link: π Question Link
π§© Problem Description
Given a 2D matrix mat[][]
with dimensions nΓm
, find the maximum possible sum of any submatrix within the given matrix.
A submatrix is any contiguous rectangular region within the matrix. The goal is to find the submatrix with the largest sum of all its elements.
π Examples
Example 1
Input: mat[][] = [[1, 2, -1, -4, -20], [-8, -3, 4, 2, 1], [3, 8, 10, 1, 3], [-4, -1, 1, 7, -6]]
Output: 29
Explanation: The matrix is as follows and the green rectangle denotes the maximum sum rectangle
which is equal to 29.
Example 2
Input: mat[][] = [[-1, -2], [-3, -4]]
Output: -1
Explanation: Taking only the first cell is the optimal choice.
π Constraints
$1 \le n, m \le 300$
$-1000 \le \text{mat}[i][j] \le 1000$
β
My Approach
The optimal approach uses Column Compression technique combined with Kadane's Algorithm to efficiently find the maximum sum rectangle:
Column Compression + Kadane's Algorithm
Fix Column Boundaries:
Use two pointers
l
(left column) andr
(right column) to define column boundaries.For each pair of columns, we compress the 2D problem into a 1D problem.
Column Compression:
Create a temporary array
temp[]
of sizem
(number of rows).For columns from
l
tor
, sum all elements row-wise intotemp[]
.This converts the 2D submatrix problem into finding maximum subarray in 1D.
Apply Kadane's Algorithm:
On the compressed 1D array
temp[]
, apply Kadane's algorithm to find maximum subarray sum.This gives us the maximum sum rectangle with column boundaries from
l
tor
.
Track Global Maximum:
Update the global maximum across all possible column boundary combinations.
Continue until all column pairs are processed.
Algorithm Flow:
Outer loop: Fix left column boundary
l
Inner loop: Extend right column boundary
r
For each (
l
,r
) pair, compress and apply Kadane'sReturn the maximum sum found
π Time and Auxiliary Space Complexity
Expected Time Complexity: O(nΒ²m), where n is the number of columns and m is the number of rows. We iterate through all possible column pairs O(nΒ²) and for each pair, we apply Kadane's algorithm which takes O(m) time.
Expected Auxiliary Space Complexity: O(m), where m is the number of rows. We use a temporary array of size m to store the compressed column sums.
π§βπ» Code (C++)
class Solution {
public:
int maxRectSum(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size(), res = INT_MIN;
for (int l = 0; l < n; l++) {
vector<int> temp(m, 0);
for (int r = l; r < n; r++) {
for (int i = 0; i < m; i++) temp[i] += mat[i][r];
int sum = 0, maxSum = temp[0];
for (int x : temp) {
sum = max(x, sum + x);
maxSum = max(maxSum, sum);
}
res = max(res, maxSum);
}
}
return res;
}
};
β Code (Java)
class Solution {
public int maxRectSum(int mat[][]) {
int m = mat.length, n = mat[0].length, res = Integer.MIN_VALUE;
for (int l = 0; l < n; l++) {
int[] temp = new int[m];
for (int r = l; r < n; r++) {
for (int i = 0; i < m; i++) temp[i] += mat[i][r];
int sum = 0, maxSum = temp[0];
for (int x : temp) {
sum = Math.max(x, sum + x);
maxSum = Math.max(maxSum, sum);
}
res = Math.max(res, maxSum);
}
}
return res;
}
}
π Code (Python)
class Solution:
def maxRectSum(self, mat):
m, n, res = len(mat), len(mat[0]), float('-inf')
for l in range(n):
temp = [0] * m
for r in range(l, n):
for i in range(m):
temp[i] += mat[i][r]
sum_val, max_sum = 0, temp[0]
for x in temp:
sum_val = max(x, sum_val + x)
max_sum = max(max_sum, sum_val)
res = max(res, max_sum)
return res
π§ Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: π¬ Any Questions?. Let's make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated