Back to Practice Dashboard
Competitive ProgrammingHard

Maximum Sum Rectangle

Learn how to solve the 'Maximum Sum Rectangle' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Hard

Write a function max_sum_rectangle(matrix) that finds and returns the maximum sum of a sub-matrix in a 2D matrix of integers.

Constraints
  • 1 <= len(matrix), len(matrix[0]) <= 100
  • -1000 <= matrix[i][j] <= 1000

Examples

Example 1
Input
max_sum_rectangle([[1, 2, -1, -4, -20], [-8, -3, 4, 2, 1], [3, 8, 10, 1, 3], [-4, -1, 1, 7, -6]])
Output
29
Explanation

The sub-matrix from row 1, column 1 to row 3, column 3 has the maximum sum of 29.

Example 2
Input
max_sum_rectangle([[-1, -2], [-3, -4]])
Output
-1
Explanation

The maximum sum is -1, which is the cell at (0, 0).

Need a Hint?
Define subproblem states, establish the recurrence relation, and use memoization (top-down) or tabulation (bottom-up).
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor