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
ltor, 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
ltor.
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
lInner loop: Extend right column boundary
rFor 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++)
β Code (Java)
π Code (Python)
π§ 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