Maximum-Sum Submatrix
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
A field of R rows and C columns is divided into cells; grid[i][j] is the profit of the cell in row i, column j
(negative means a loss). Choose one axis-aligned rectangle of cells (at least one cell) and collect the profit of every
cell inside it. Return the maximum total profit.
Examples
| grid | result |
|---|---|
[[1, -2, 3], [-4, 5, 6], [7, -8, 9]] | 18 |
[[-5, -2], [-3, -9]] | -2 |
[[2, 3, -100, 4]] | 5 |
Example 1 — The whole right column: 3 + 6 + 9 = 18.
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(grid: int[][]) → long
Constraints
-
grid.length,grid[i].length(all rows have the same length) -
grid[i][j] - The answer may exceed 32 bits.
Expected complexity
- Time
- O(R^2 * C)
- Space
- O(C)
Examples
| grid | Expected |
|---|---|
[[1,-2,3],[-4,5,6],[7,-8,9]] | 18 |
[[-5,-2],[-3,-9]] | -2 |
[[2,3,-100,4]] | 5 |
Hint
Hint
Fix the top and bottom rows; summing each column over that band gives an array col whose maximum subarray sum (Kadane,
) is the best rectangle for the band. Extending bottom adds one row to col, so the total is . Use
64-bit sums. Checking every rectangle with 2D prefix sums is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 3490 ms | derived |
| Java 25 | 1034 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 11 | verdict only |
| performance | 60 | 4 | verdict only |