-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax-sum-of-rectangle-no-larger-than-k.cpp
55 lines (50 loc) · 1.81 KB
/
max-sum-of-rectangle-no-larger-than-k.cpp
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Solution {
public:
int maxSumSubmatrix1(vector<vector<int>>& matrix, int k) {
if (matrix.empty()) return 0;
int row = matrix.size(), col = matrix[0].size(), res = INT_MIN;
for (int l = 0; l < col; ++l) {
vector<int> sums(row, 0);
for (int r = l; r < col; ++r) {
for (int i = 0; i < row; ++i) {
sums[i] += matrix[i][r];
}
// Find the max subarray no more than K
set<int> accuSet;
accuSet.insert(0);
int curSum = 0, curMax = INT_MIN;
for (int sum : sums) {
curSum += sum;
set<int>::iterator it = accuSet.lower_bound(curSum - k);
if (it != accuSet.end()) curMax = std::max(curMax, curSum - *it);
accuSet.insert(curSum);
}
res = std::max(res, curMax);
}
}
return res;
}
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
int res=INT_MIN;
int row=matrix.size();
if(row==0) return 0;
int col=matrix[0].size();
for(int l=0;l<col;l++){
vector<int> tmp(row,0);
for(int r=l;r<col;r++){
for(int i=0;i<row;i++) tmp[i]+=matrix[i][r];
set<int> us;// 由于后面要使用lower_bound,所以要求有序
us.emplace(0);
int pre_sum=0;
for(int i=0;i<row;i++){
pre_sum+=tmp[i];
auto it=lower_bound(us.begin(),us.end(),pre_sum-k);
// auto it=us.lower_bound(pre_sum-k);
if(it!=us.end()) res=max(res,pre_sum-*it);
us.emplace(pre_sum);
}
}
}
return res;
}
};