Competitive ProgrammingHard

Maximum Sum Rectangle

Detailed guide and Python implementation for the 'Maximum Sum Rectangle' problem.

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?
Consider using Dynamic Programming-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

Ready to Solve?

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

Open in Editor

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.