# 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:

1. The rectangle inside the matrix must have an area > 0.
2. What if the number of rows is much larger than the number of columns?

Credits:
Special thanks to @fujiaozhu for adding this problem and creating all test cases.

``````class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
if (matrix.empty() || matrix[0].empty()) return 0;
int m = matrix.size(), n = matrix[0].size(), res = INT_MIN;
int sum[m][n];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
int t = matrix[i][j];
if (i > 0) t += sum[i - 1][j];
if (j > 0) t += sum[i][j - 1];
if (i > 0 && j > 0) t -= sum[i - 1][j - 1];
sum[i][j] = t;
for (int r = 0; r <= i; ++r) {
for (int c = 0; c <= j; ++c) {
int d = sum[i][j];
if (r > 0) d -= sum[r - 1][j];
if (c > 0) d -= sum[i][c - 1];
if (r > 0 && c > 0) d += sum[r - 1][c - 1];
if (d <= k) res = max(res, d);
}
}
}
}
return res;
}
};
``````

``````class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
if (matrix.empty() || matrix[0].empty()) return 0;
int m = matrix.size(), n = matrix[0].size(), res = INT_MIN;
for (int i = 0; i < n; ++i) {
vector<int> sum(m);
for (int j = i; j < n; ++j) {
for (int k = 0; k < m; ++k) {
sum[k] += matrix[k][j];
}
int curSum = 0;
set<int> st{{0}};
for (auto a : sum) {
curSum += a;
auto it = st.lower_bound(curSum - k);
if (it != st.end()) res = max(res, curSum - *it);
st.insert(curSum);
}
}
}
return res;
}
};
``````

Github 同步地址：

https://github.com/grandyang/leetcode/issues/363

Maximum Subarray

Range Sum Query 2D - Immutable

Maximum Size Subarray Sum Equals k

https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/

https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/83618/2-Accepted-Java-Solution

https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/discuss/83599/Accepted-C%2B%2B-codes-with-explanation-and-references

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation