Practice › Arrays
Maximum Sum Rectangle
Hard · Arrays · Asked at Amazon, Google, Microsoft, Samsung
Find the sub-matrix (a rectangle of one or more cells, rows and columns contiguous) with the largest sum, and print that sum.
Input
First line: R C. Next R lines: C integers each.
Output
The largest rectangle sum.
Constraints
- 1 ≤ R, C ≤ 150
- −1000 ≤ a[i][j] ≤ 1000
Fix a top row and a bottom row; add each column between them into one array. The best rectangle with those rows is the maximum subarray of that array (Kadane). Trying all row pairs costs O(R² × C).
Example 1
Input
4 5 1 2 -1 -4 -20 -8 -3 4 2 1 3 8 10 1 3 -4 -1 1 7 -6
Output
29
Example 2
Input
2 2 -3 -2 -5 -1
Output
-1
Hints
- Fix which rows the rectangle covers: a top row and a bottom row.
- Squash those rows into one array by adding each column.
- The best rectangle for those rows is the maximum subarray of that array — Kadane.
Approach
For every top row, start a column-sum array of zeros. Extend the bottom row one at a time, adding that row into the column sums, and run Kadane's algorithm on the column sums. Kadane keeps the best subarray ending at each column: cur = max(col[j], cur + col[j]). The answer is the best value seen over all row pairs. Because a rectangle must have at least one cell, an all-negative matrix returns its largest element.
Complexity: O(R² · C) time · O(C) extra space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int R, C;
cin >> R >> C;
vector<vector<long long>> a(R, vector<long long>(C));
for (auto &row : a)
for (auto &x : row) cin >> x;
long long best = LLONG_MIN;
for (int top = 0; top < R; top++) {
vector<long long> col(C, 0);
for (int bot = top; bot < R; bot++) {
long long cur = 0;
for (int j = 0; j < C; j++) {
col[j] += a[bot][j];
cur = (j == 0) ? col[j] : max(col[j], cur + col[j]);
best = max(best, cur);
}
}
}
cout << best << "\n";
return 0;
}Python solution
import sys
data = sys.stdin.buffer.read().split()
R, C = int(data[0]), int(data[1])
a = [list(map(int, data[2 + i * C : 2 + (i + 1) * C])) for i in range(R)]
best = None
for top in range(R):
col = [0] * C
for bot in range(top, R):
row = a[bot]
cur = 0
for j in range(C):
col[j] += row[j]
v = col[j]
cur = v if j == 0 or cur < 0 else cur + v
if best is None or cur > best:
best = cur
print(best)Java solution
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int R = (int) in.nval;
in.nextToken();
int C = (int) in.nval;
long[][] a = new long[R][C];
for (int i = 0; i < R; i++)
for (int j = 0; j < C; j++) {
in.nextToken();
a[i][j] = (long) in.nval;
}
long best = Long.MIN_VALUE;
for (int top = 0; top < R; top++) {
long[] col = new long[C];
for (int bot = top; bot < R; bot++) {
long cur = 0;
for (int j = 0; j < C; j++) {
col[j] += a[bot][j];
cur = (j == 0) ? col[j] : Math.max(col[j], cur + col[j]);
best = Math.max(best, cur);
}
}
}
System.out.println(best);
}
}