Given an m x n integer matrix, find the sub-rectangle (contiguous rows and columns) with the maximum possible sum and return that sum. Optionally return the rectangle coordinates (top, left) and (bottom, right).
Input:
mat =[[1,-2,0,-15],[2,3,-1,4],[-1,2,5,-3]]Output: 10Explanation: The maximum-sum rectangle is the 2x3 sub-rectangle covering rows 1..2 and columns 1..3, shown in green in diagram.
Fix two column boundaries left and right. Collapse the columns between them into a 1D array tmp[row] holding the row-wise sums between left and right. The maximum-sum rectangle that spans those columns is the maximum subarray of tmp (Kadane). Iterate all column pairs.
classSolution {
public:longlong maxSumSubmatrix(const std::vector<std::vector<int>>& A) {
int rows = A.size();
if (rows ==0) return0;
int cols = A[0].size();
longlong best = LLONG_MIN;
for (int left =0; left < cols; ++left) {
std::vector<longlong> tmp(rows, 0);
for (int right = left; right < cols; ++right) {
for (int r =0; r < rows; ++r) tmp[r] += A[r][right];
// Kadane on tmp
longlong cur = tmp[0], curBest = tmp[0];
for (int i =1; i < rows; ++i) {
cur = std::max(tmp[i], cur + tmp[i]);
curBest = std::max(curBest, cur);
}
best = std::max(best, curBest);
}
}
return best;
}
};
classSolution {
publiclongmaxSumSubmatrix(int[][] A) {
int rows = A.length;
if (rows == 0) return 0;
int cols = A[0].length;
long best = Long.MIN_VALUE;
for (int left = 0; left < cols; left++) {
long[] tmp =newlong[rows];
for (int right = left; right < cols; right++) {
for (int r = 0; r < rows; r++) tmp[r]+= A[r][right];
long cur = tmp[0], curBest = tmp[0];
for (int i = 1; i < rows; i++) {
cur = Math.max(tmp[i], cur + tmp[i]);
curBest = Math.max(curBest, cur);
}
best = Math.max(best, curBest);
}
}
return best;
}
}
from typing import List
classSolution:
defmax_sum_submatrix(self, A: List[List[int]]) -> int:
rows = len(A)
if rows ==0:
return0 cols = len(A[0])
best = float('-inf')
for left in range(cols):
tmp = [0] * rows
for right in range(left, cols):
for r in range(rows):
tmp[r] += A[r][right]
cur = tmp[0]
cur_best = tmp[0]
for x in tmp[1:]:
cur = max(x, cur + x)
cur_best = max(cur_best, cur)
best = max(best, cur_best)
return best