363. Max Sum of Rectangle No Larger Than K
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:
Input: matrix = [[1,0,1],[0,-2,3]], k = 2
Output: 2
Explanation: 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?
方法1: Kadane’s algorithm + binary search
discussion: https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/83599/Accepted-C%2B%2B-codes-with-explanation-and-references
Tushar: https://www.youtube.com/watch?v=yCQN096CwWM&feature=youtu.be
思路:
主体思路和上面视频中的kadane’s 一样,首先整体是以双层循环扫描每一列,也就是O(n ^ 2)。在每一次内层扫描中,计算一个row-wise的累计和vector,每次获得的vector,用largest substring 的方法找到行列都累加起来的累计和最大范围,更新left,right,up,down的index来记录全球最大。而每一次找largest substring的方法运用了binary search,来避免O(m ^ 2)。具体来讲:因为sums[i,j] = sums[i] - sums[j],then sums[i,j] is target subarray that needs to have sum <= k,sums[j] is known current cumulative sum。And we use binary search to find sums[i]. Therefore sums[i] needs to have sum >= sums[j] - k,复杂度降为O(m log m)。
Complexity
Time complexity: O[min(m,n)^2 * max(m,n) * log(max(m,n))]
Space complexity: O(max(m, n)).
class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
int m = matrix.size(), n = matrix[0].size();
int res = INT_MIN;
for (int l = 0; l < n; l++) {
vector<int> rowsum(m, 0);
for (int r = l; r < n; r++) {
int sum = 0;
set<int> sumset;
// 首先应该将0 insert,那么当 curSum 和k相等时,0就可以被返回了。至少应该有0.
sumset.insert(0);
for (int i = 0; i < m; i++) {
rowsum[i] += matrix[i][r];
sum += rowsum[i];
auto it = lower_bound(sumset.begin(), sumset.end(), sum - k);
if (it != sumset.end()) res = max(res, sum - *it);
// 必须在查找后插入,因为当k = 0 的情况,不应该包含自己
sumset.insert(sum);
}
}
}
return res;
}
};