LeetCode 363. Max Sum of Rectangle No Larger Than K

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
const int m = matrix.size(), n = matrix[0].size();
int ans = INT_MIN;
for (int i = 0; i < m; ++i) { // enumerate upper bound.
vector<int> sum(n);
for (int j = i; j < m; ++j) { // enumerate lower bound.
for (int c = 0; c < n; ++c)
sum[c] += matrix[j][c]; // area sum of each column.
// find the largest value that is
// 1. smaller than k,
// 2. from a continue subarray of `sum`.
set<int> sumSet{0};
int s = 0;
for (int v : sum) {
s += v;
auto it = sumSet.lower_bound(s - k);
if (it != sumSet.end())
ans = max(ans, s - *it);
sumSet.insert(s);
}
}
}
return ans;
}
};