Explaining Kadane's and max submatrix sum algorithms
Kadane's algorithm finds the maximum subarray sum in O(n) by tracking a running max ending at each position and a global max. For the max submatrix sum in an N×N matrix, fix pairs of rows and compress the columns between them into a 1D array, then apply Kadane's in O(N). Doing this for all O(N²) row pairs gives O(N³) total complexity. This approach efficiently extends the 1D max subarray solution to 2D.
1) Maximum Subarray via Kadane’s Algorithm (O(N)):
Given a 1D array arr[0..N-1], Kadane’s algorithm finds the maximum sum over all contiguous subarrays:
def max_subarray(arr):
current = arr[0]
best = arr[0]
for x in arr[1:]:
current = max(x, current + x)
best = max(best, current)
return best
At each step, current represents the best subarray ending at the current position; best tracks the overall maximum. This runs in O(N).
2) Maximum Submatrix Sum in an N×N Matrix (O(N³)):
To extend Kadane’s idea to 2D, we fix the top and bottom rows of the submatrix, compress the rows in between into a 1D array of column sums, then apply Kadane’s on that array:
- For each possible pair of rows
(top, bottom) (there are O(N²) such pairs):
- Create a temporary array
temp of length N, initialized to 0.
- For each column
c, sum up the elements from top to bottom in that column:
temp[c] += matrix[bottom][c] (repeated as bottom advances).
- Apply Kadane’s algorithm to
temp to find the best subarray sum for these rows.
- Track the maximum sum found across all pairs of
(top, bottom).
Because there are O(N²) pairs of rows and each Kadane run is O(N), the total time is O(N³).
Below is one possible Python implementation:
def max_submatrix_sum(matrix):
n = len(matrix)
best = float('-inf')
for top in range(n):
temp = [0] * n
# bottom goes from top to last row
for bottom in range(top, n):
# Accumulate sums for columns between top..bottom
for c in range(n):
temp[c] += matrix[bottom][c]
# Run 1D Kadane on temp
current = temp[0]
best_kadane = temp[0]
for x in temp[1:]:
current = max(x, current + x)
best_kadane = max(best_kadane, current)
best = max(best, best_kadane)
return best
Explanation:
temp[c] collects the sum of matrix elements from row top through bottom in column c.
- Kadane’s on
temp gives the maximum subarray sum across columns for these row bounds.
- Checking all
(top, bottom) pairs ensures every possible submatrix is considered.
- Total complexity: O(N²) for row-pair loops × O(N) for Kadane each time = O(N³).
This returns the maximum possible sum of any rectangular submatrix in the N×N input.