题目:
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix such that its sum is no larger than k.
Example:
Given matrix = [ [1, 0, 1], [0, -2, 3] ] k = 2
The answer is 2
. Because the sum of rectangle [[0, 1], [-2, 3]]
is 2 and 2 is the max number no larger than k (k = 2).
Note:
- The rectangle inside the matrix must have an area > 0.
- What if the number of rows is much larger than the number of columns?
思路:
为分析方便我们假设矩阵有m行n列。一种暴力解法就是枚举每个矩形块,这种算法的时间复杂度是O((mn)^2),但是我们采用二分查找法进行优化可以将时间复杂度降低到O(n^2mlogm)。以下面的代码为例进行解释:我们枚举列[i, j]之间的数据之和,下面的定义中,sum[x]表示在列i到列j之间,第x行元素的累计和(也就是从matrix[x][i]到matrix[x][j]之间的元素和),而cur_sum表示在列i到列j区间之间,从第0行到第x行之间的数据元素之和(也就是从matrix[0][i]到matrix[x][j]之间的元素和)。明白sum数组和cur_sum的含义是理解本算法的关键。然后我们建立一个二叉搜索树(本文中用set实现)。每次得到一个新的cur_sum时,我们搜索一个此前存在在二叉搜索树中的累积和num,使得cur_sum - num <= k(这意味着在列[i, j]区间,从num所在的行到当前行的所有元素的和小于等于k)。如果这样的num存在,它就是一个潜在解,我们据此更新全局最优值。该算法的空间复杂度是O(m)(主要是累积和sum数组和二叉搜索树st占用了O(m)的空间)。那么如果行个数远大于列个数呢(m >> n)?这种情况下时间复杂度不会增长太快,但是空间复杂度将会增长较大。如果在具体应用中对空间复杂度的要求比较高,那么我们可以反过来枚举任意两行之间数据累积和,这样空间复杂度可以降低到O(n),但是时间复杂度却会升高到O(m^2nlogn),所以我感觉是一个trade off。
代码:
class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
if(matrix.size() == 0 || matrix[0].size() == 0) {
return 0;
}
int row = matrix.size(), col = matrix[0].size();
int ans =INT_MIN;
for(int i = 0; i < col; i++) { // the start col
vector<int> sum(row, 0);
for(int j = i; j < col; j++) { // the end col
set<int> st{0};
int cur_sum = 0, cur_max = INT_MIN;
for(int x = 0; x < row; ++x) { // for each row
sum[x] += matrix[x][j];
cur_sum += sum[x];
auto it = st.lower_bound(cur_sum - k);
if(it != st.end()) {
cur_max = max(cur_sum - (*it), cur_max);
}
st.insert(cur_sum);
}
ans = max(cur_max, ans);
}
}
return ans;
}
};