maximum sum subrectangle in a sparse matrix
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
The maximum-sum subrectangle problem asks for the axis-aligned rectangle inside a matrix whose entries add up to the largest possible value. In dense matrices, the classic solution is a two-dimensional form of Kadane’s algorithm. In sparse matrices, the same core idea still matters, but you gain extra leverage by avoiding needless work on the many zero entries.
Dense Baseline: 2D Kadane
The standard dense solution fixes a left column and a right column, compresses everything between them into a one-dimensional row-sum array, and then runs Kadane’s maximum-subarray algorithm on that array.
If the matrix has R rows and C columns, this gives a typical time cost of O(C^2 * R) or O(R^2 * C) depending on which dimension you compress.
Kadane for one dimension:
That one-dimensional routine is the engine inside the 2D solution.
Sparse Matrices Change the Engineering Tradeoff
If most entries are zero, converting the whole matrix to dense form and scanning every cell may waste a lot of time and memory. The key sparse insight is that zero entries do not need to be stored explicitly, and row accumulations only need to change when a nonzero element contributes inside the active column range.
There are two broad cases:
- the matrix dimensions are moderate, but values are mostly zero
- the matrix dimensions are huge, and only a small set of coordinates are nonzero
In the first case, a sparse-friendly accumulation strategy often helps. In the second, coordinate compression becomes much more important.
Practical Sparse-Friendly Approach
Suppose the matrix is stored row by row as dictionaries of nonzero columns. Then for each left-right column pair, you only add entries that actually exist in that range.
A simple representation:
A sparse-friendly implementation can look like this:
This still follows the dense algorithm’s structure, but it uses sparse row storage so the matrix itself is not stored densely.
Coordinate Compression for Very Large Sparse Grids
If row and column indices are very large but only a few positions are nonzero, another useful technique is coordinate compression.
The idea is:
- collect all rows and columns that contain nonzero values
- map them into a smaller dense index space
- solve the problem on the compressed grid
This does not eliminate all complexity, but it can reduce a huge mostly empty problem into one whose effective size matches the nonzero structure rather than the raw coordinate range.
The catch is that compression must preserve rectangle semantics correctly. That makes the implementation more subtle than ordinary sparse storage.
Watch the All-Negative Case
The maximum rectangle is not always a large region. If every value is negative, the correct answer is the least negative single cell.
That is why Kadane’s implementation must be written carefully. A version that resets to zero blindly can produce the wrong answer on all-negative input.
Choosing the Compression Dimension
In the dense algorithm, you usually compress the smaller dimension to reduce work. The same idea still applies here. If there are far fewer rows than columns, compress over columns and run Kadane on rows. If the opposite is true, transpose the logic.
This choice affects constant factors a lot even when the asymptotic formula looks similar.
Common Pitfalls
The most common mistake is assuming sparsity automatically changes the asymptotic problem completely when the basic left-right compression logic is still the right foundation. Another is writing a Kadane implementation that fails on all-negative row sums. Developers also often store sparse data efficiently but then immediately densify the entire matrix and lose the advantage. A final issue is forgetting to choose the compression direction based on the smaller effective dimension, which makes the implementation slower than necessary.
Summary
- The classic solution is 2D Kadane: compress one dimension and run maximum subarray on the other.
- Sparse matrices help mainly by reducing storage and avoiding needless zero handling.
- Sparse row or coordinate-based representations can make the implementation more practical.
- Kadane must handle all-negative cases correctly.
- For very large sparse coordinate spaces, coordinate compression may be necessary before solving the rectangle problem efficiently.
Related reading
- Maximum weighted bipartite matching, constraint ordering of each graph is preserved
- Maximum xor among all subsets of an array
- MD5 vs CRC32 Which one's better for common use?
- Meaning of the ⊥ symbol in distributed algorithm context
- Maximum surface inside a triangle
- Maximum volume inscribed ellipsoid in a polytope/set of points
- Mean value and standard deviation of a very huge data set
- Median of a Matrix with sorted rows

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.