Getting the submatrix with maximum sum?
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 submatrix problem asks for a contiguous rectangular region in a 2D matrix whose elements add up to the largest possible value. The standard efficient solution is a 2D extension of Kadane's algorithm: fix a pair of row boundaries, compress the rows into a 1D array of column sums, and run the maximum-subarray algorithm on that array.
That turns a hard 2D search into a manageable series of 1D problems. It is much faster than checking every possible rectangle directly and is the usual interview or production answer when the matrix is dense.
Why the Naive Approach Is Too Slow
A submatrix is defined by four boundaries:
- top row
- bottom row
- left column
- right column
If you try every combination and sum the rectangle from scratch, the work grows too quickly. Even if prefix sums make each rectangle sum fast, you still have to examine all possible boundaries, which is too expensive for anything but small inputs.
The key optimization is to stop treating the full 2D rectangle as the primary unit of work.
Reduce the 2D Problem to Repeated 1D Problems
Fix a top row and a bottom row. For those row boundaries, each column can be collapsed into a single number: the sum of the entries in that column between those two rows.
Once you do that, the best left and right column boundaries are exactly the maximum-sum contiguous subarray of the collapsed array.
So the high-level strategy becomes:
- choose a top row
- extend the bottom row downward one row at a time
- update a running array of column sums
- run Kadane's algorithm on that array
- keep the best rectangle seen so far
This reduces the time complexity to O(rows^2 * cols) when Kadane runs in O(cols).
Kadane's Algorithm with Coordinates
For this problem, Kadane's algorithm needs to return not just the best sum but also the start and end column indices.
Starting from arr[0] rather than 0 is important because it handles the all-negative case correctly.
Full 2D Solution in Python
This returns both the maximum sum and the rectangle coordinates.
Reconstruct the Rectangle
If you need the actual submatrix values, use the saved coordinates.
That separation is useful because some callers only need the score, while others need the rectangle contents too.
Complexity and Practical Notes
If there are r rows and c columns, the row-compression approach is O(r^2 * c) and uses O(c) extra space for the temporary column-sum array.
If the matrix is much wider than it is tall, you can transpose the idea and compress columns instead. The algorithm stays the same conceptually, but you choose the smaller dimension for the squared outer loop when possible.
Common Pitfalls
The biggest mistake is using a Kadane implementation that resets the running sum to zero unconditionally, which fails for all-negative matrices. Another is recomputing the collapsed column sums from scratch for every row pair instead of updating them incrementally. Developers also often forget to track the rectangle coordinates and end up with only the sum when the problem requires the actual submatrix. Finally, when the matrix can be empty, the code should validate input before indexing matrix[0].
Summary
- The efficient solution is a 2D extension of Kadane's algorithm.
- Fix row pairs, compress them into a 1D column-sum array, and run Kadane on that array.
- The resulting complexity is
O(rows^2 * cols). - Track coordinates along with the best sum if you need the rectangle itself.
- Handle all-negative inputs and empty-input validation carefully.
Related reading
- Git Confusion about merge algorithm, conflict format, and interplay with mergetools
- Given 2 sorted arrays of integers, find the nth largest number in sublinear time
- Given a 1 TB data set on disk with around 1 KB per data record, how can I find duplicates using 512 MB RAM and infinite disk space?
- Given a bitonic array and element x in the array, find the index of x in 2logn time
- Getting time elapsed in Objective-C
- Getting value of enum on string conversion
- Given a list of date ranges, find a date which occurs maximum times
- Given a list of dictionaries, how can I eliminate duplicates of one key, and sort by another

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.