Maximum Sum Subgrid Finder
Problem Description
Given an `m x n` integer matrix `grid` (which may contain negative values), find the submatrix (contiguous rectangular region) with the largest sum and return that sum.
A submatrix is defined by choosing row indices `r1 <= r2` and column indices `c1 <= c2`, and summing all `grid[i][j]` for `r1 <= i <= r2`, `c1 <= j <= c2`.
**Example 1:**
```
Input: grid = [[2,-1,3],[-4,6,1],[1,-2,4]]
Output: 14
Explanation: The submatrix rows 0–2, cols 1–2 gives -1+3+6+1-2+4 = 11?
Actually rows 1–2 cols 1–2: 6+1-2+4 = 9, but rows 0–2 cols 1–2 = -1+3+6+1-2+4=11.
Max is the full matrix sum if needed but row1-2 col1-2 = 9...
Actually rows 0–2 all cols: 2-1+3-4+6+1+1-2+4 = 10. Best is rows 1 col 1 = 6, or rows 1-2 col 1-2 = 9.
Output: 14
Explanation: Submatrix spanning rows 0-2, cols 0 and 2 isn't contiguous. Submatrix rows 0–2 cols 0–2 sums to 10. Rows 0–1 cols 1–2 = -1+3+6+1=9. Rows 1 cols 0–2 = -4+6+1=3. Best contiguous: rows 0-2 col 2 = 3+1+4=8. Row 1 col1 alone=6. Rows 1-2 cols 1-2 = 6+1-2+4=9. Row 0-2 col 1-2 = (-1+3)+(6+1)+(-2+4)=2+7+2=11. Rows 1-2 col 0-2=-4+6+1+1-2+4=6. Hmm let me recompute for output 14.
Input: grid = [[2,-1,3],[-4,6,1],[5,-2,4]]
Output: 14
Explanation: Rows 1–2, cols 0–2: -4+6+1+5-2+4 = 10. Rows 1–2 cols 1–2: 6+1-2+4=9. Rows 2 col 0-2: 5-2+4=7. Row 0-2 col 0-2: 2-1+3-4+6+1+5-2+4=14. Full matrix = 14.
```
**Example 2:**
```
Input: grid = [[-3,-1],[-2,-4]]
Output: -1
Explanation: All values are negative; the best single cell is -1.
```
Constraints
- 1 <= m, n <= 100
- -100 <= grid[i][j] <= 100
- m == grid.length
- n == grid[0].length
Follow-up
Can you solve this in O(m × n²) time by applying the 2D Kadane variant more efficiently?
Hints
Try the problem first. If you get stuck, you can reveal hints one at a time.
Solution
Leaderboard
No entries yet for python.
Be the first — submit an accepted solution.