Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
max-sum-of-sub-matrix-no-larger-than-k.cpp 1.22 KB
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-06-22 14:37 +08:00 . Update max-sum-of-sub-matrix-no-larger-than-k.cpp
// Time: O(min(m, n)^2 * max(m, n) * log(max(m, n)))
// Space: O(max(m, n))
class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
if (matrix.empty()) {
return 0;
}
const int m = min(matrix.size(), matrix[0].size());
const int n = max(matrix.size(), matrix[0].size());
int result = numeric_limits<int>::min();
for (int i = 0; i < m; ++i) {
vector<int> sums(n, 0);
for (int j = i; j < m; ++j) {
for (int l = 0; l < n; ++l) {
sums[l] += (m == matrix.size()) ? matrix[j][l] : matrix[l][j];
}
// Find the max subarray no more than K.
set<int> accu_sum_set;
accu_sum_set.emplace(0);
int accu_sum = 0;
for (int sum : sums) {
accu_sum += sum;
auto it = accu_sum_set.lower_bound(accu_sum - k);
if (it != accu_sum_set.end()) {
result = max(result, accu_sum - *it);
}
accu_sum_set.emplace(accu_sum);
}
}
}
return result;
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助