VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-rectangle-in-a-2d-matrix/

⇱ Maximum sum rectangle in a 2D matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum rectangle in a 2D matrix

Last Updated : 27 Feb, 2026

Given a 2D matrix mat[][] of integers, find the maximum sum among all possible submatrices.

Example:

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.

👁 maximum---------sum---------rectangle---------in---------a---------2d---------matrix---------3

This problem is mainly an extension of the Maximum Subarray Sum.

[Naive approach] - Iterating Over All Possible Submatrices - O((n*m)3) time and O(1) space

We explore all possible rectangles in the given 2D array, by using four variables: two to define the left and right boundaries and two more to define the top and bottom boundaries and calculate their sums, and keep track of the maximum sum found.

[Better Approach] - Using Prefix Sum - O((n*m)2) time and O(n*m) space

In this approach, we used prefix sum matrix to efficiently compute the sum of any submatrix. We first precompute the prefix sum such that pref[i][j] stores the sum of all elements in the submatrix from the top-left corner (0, 0) to the cell (i, j). This preprocessing allows us to calculate the sum of any arbitrary submatrix in constant time using the inclusion-exclusion principle, thereby eliminating redundant computations and significantly improving performance.

Step by Step Approach:

  • Initialize a 2D prefix sum matrix pref[][] of the same size as the input matrix.
  • Precompute the prefix sum for each cell : pref[i][j] = matrix[i][j] + pref[i−1][j] + pref[i][j−1] − pref[i−1][j−1] (Handle edges separately to avoid index out-of-bound errors.)
  • Iterate over all possible top-left corners (up, left) and bottom-right corners (down, right) to define submatrices.
  • For each such submatrix, compute the sum using the prefix sum matrix in constant time: sum = pref[down][right] − pref[up - 1][right] − pref[down][left−1] + pref[up-1][left - 1]
  • Track the maximum sum obtained across all submatrices.

Output
29

[Expected Approach] - Using Kadane’s Algorithm - O(n*m2) time and O(n) space

Instead of checking every possible submatrix, we fix two column boundaries: left and right. For each pair of columns, we compress the 2D matrix into a 1D array, where each element represents the sum of rows between the current left and right columns. This 1D array (temp[]) represents the column-wise sum for a fixed column window.
Now, we can apply Kadane’s algorithm on this temp[] array to find the maximum subarray sum, which corresponds to a rectangular submatrix with the maximum sum between columns left and right.


Output
29
Comment