-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmaxSumSubmatrix.cpp
More file actions
28 lines (27 loc) · 993 Bytes
/
maxSumSubmatrix.cpp
File metadata and controls
28 lines (27 loc) · 993 Bytes
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
class Solution {
public:
int maxSumSubmatrix(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 = max(curMax, curSum - *it);
accuSet.insert(curSum);
}
res = max(res, curMax);
}
}
return res;
}
};