v9.1.1
Menu

Maximum Sum Rectangle in Image

hardFREEDynamic ProgrammingDynamic Programming, KadaneCV - DSA

Problem Statement

In image processing, finding regions of interest often involves locating rectangular areas with maximum pixel intensity sum.

Given a 2D matrix representing pixel intensities (can be negative for edge-detected images), find the maximum sum of any rectangular sub-region (contiguous rows and contiguous columns). The rectangle must contain at least one cell, so for an all-negative matrix the answer is its largest single value. Return the sum as an integer.

This is useful for:

  • Detecting bright regions in astronomical images
  • Finding high-contrast areas after edge detection
  • Locating regions of interest in thermal imaging

Constraints

  • 1≤rows,cols≤1001 \leq rows, cols \leq 100
  • −1000≤matrix[i][j]≤1000-1000 \leq matrix[i][j] \leq 1000

Example

Input
matrix = [[1, -2, 3], [-4, 5, -6], [7, -8, 9]]
Output
9
Reasoning
  • Input: matrix is a 3×33 \times 3 grid of signed pixel intensities. A rectangle is any block of contiguous rows and contiguous columns; its score is the sum of its cells.
  • There are 6×6=366 \times 6 = 36 such rectangles, from single cells to the whole grid.
  • Negatives drag big blocks down: the whole grid sums to 55, the right column to 3−6+9=63-6+9 = 6.
  • The strongest full row is the bottom one: 7+(−8)+9=87 + (-8) + 9 = 8. Growing it upward hurts: the bottom two rows give 8+(−5)=38 + (-5) = 3, and all three rows give 3+2=53 + 2 = 5, both below 88.
  • Trimming the bottom row to its right cell alone gives 9>89 > 8, because the dropped pair 7+(−8)=−17 + (-8) = -1 was a net loss. So the answer is 9, a 1×11 \times 1 rectangle.
  • Output: a single integer, the best rectangle sum. Notice the rectangle can't be empty, so an all-negative grid with cells −1,−2,−3,−4-1, -2, -3, -4 gives −1-1, not 00.

More from CV - DSA

solution.py

Test results

Sign in to run your code against the test cases.