Maximum sum rectangle in a 2D matrix

Pattern: 2D grid DP

hard

Fix the left and right columns, add up each row between them, and run Kadane's algorithm on those row sums to find the best band of rows. The best over all column pairs is the answer.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return the largest sum of any rectangle (a block of consecutive rows and columns) in the matrix. The catalogue has no practice link for this one.

Think first

  • Which 1D problem finds the best block in an array?
  • How can a rectangle become an array?
  • How many column pairs are there?

Hints

    Brute force, and why it fails

    Try every rectangle with prefix sums: O(R² × C²).

    The key insight

    Fixing the columns reduces the rest to Maximum Subarray on row sums.

    Dry run

    The GFG 4 × 5 example. Columns 1 to 3 give row sums -3, 3, 19, 7.

    Step 1 of 2

    The plan

    for left: rows = zeros; for right: rows += column right
      Kadane on rows
    

    Complexity

    Time
    O(C² × R)
    Space
    O(R)

    Every column pair times a linear Kadane.

    Edge cases

    • All negative: the largest single value.
    • One cell.
    • All positive: the whole matrix.
    I've built my logic, show the code

    Java

    class Solution {
        public int maximumSumRectangle(int[][] mat) {
            int R = mat.length, C = mat[0].length, best = Integer.MIN_VALUE;
            for (int left = 0; left < C; left++) {
                int[] rows = new int[R];            // row sums between columns left and right
                for (int right = left; right < C; right++) {
                    for (int r = 0; r < R; r++) rows[r] += mat[r][right];
                    int cur = 0;
                    for (int v : rows) {            // Kadane on the row sums: the best band of rows for these columns
                        cur = Math.max(v, cur + v);
                        best = Math.max(best, cur);
                    }
                }
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        int maximumSumRectangle(vector<vector<int>>& mat) {
            int R = static_cast<int>(mat.size()), C = static_cast<int>(mat[0].size()), best = INT_MIN;
            for (int left = 0; left < C; left++) {
                vector<int> rows(R, 0);             // row sums between columns left and right
                for (int right = left; right < C; right++) {
                    for (int r = 0; r < R; r++) rows[r] += mat[r][right];
                    int cur = 0;
                    for (int i = 0; i < R; i++) {   // Kadane on the row sums: the best band of rows for these columns
                        cur = max(rows[i], cur + rows[i]);
                        best = max(best, cur);
                    }
                }
            }
            return best;
        }
    };

    Python

    class Solution:
        def maximumSumRectangle(self, mat: list[list[int]]) -> int:
            R, C, best = len(mat), len(mat[0]), float("-inf")
            for left in range(C):
                rows = [0] * R                      # row sums between columns left and right
                for right in range(left, C):
                    cur = 0
                    for r in range(R):
                        rows[r] += mat[r][right]
                        cur = max(rows[r], cur + rows[r])   # Kadane on the row sums
                        best = max(best, cur)
            return best

    Common mistakes

    • Kadane that never takes a negative single value.
    • Resetting row sums per column pair.

    Similar problems