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.

这道题给了我们一个二维数组,让求和不超过的K的最大子矩形,那么首先可以考虑使用 brute force 来解,就是遍历所有的子矩形,然后计算其和跟K比较,找出不超过K的最大值即可。就算是暴力搜索,也可以使用优化的算法,比如建立累加和,参见之前那道题 Range Sum Query 2D - Immutable,可以快速求出任何一个区间和,下面的方法就是这样的,当遍历到 (i, j) 时,计算 sum(i, j),表示矩形 (0, 0) 到 (i, j) 的和,然后遍历这个矩形中所有的子矩形,计算其和跟K相比,这样既可遍历到原矩形的所有子矩形,参见代码如下:

解法一:

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

下面这个算法进一步的优化了运行时间,这个算法是基于计算二维数组中最大子矩阵和的算法,可以参见 youtube 上的这个视频。这个算法巧妙在把二维数组按行或列拆成多个一维数组,然后利用一维数组的累加和来找符合要求的数字,这里用了 lower_bound 来加快的搜索速度,也可以使用二分搜索法来替代。建立一个 TreeSet,然后开始先放个0进去,为啥要放0呢,因为要找 lower_bound(curSum - k),当 curSum 和k相等时,0就可以被返回了,这样就能更新结果了。由于对于一维数组建立了累积和,那么 sum[i,j] = sum[i] - sum[j],其中 sums[i,j] 就是目标子数组需要其和小于等于k,然后 sums[j] 是 curSum,而 sum[i] 就是要找值,当使用二分搜索法找 sum[i] 时,sum[i] 的和需要大于等于 sum[j] - k,所以也可以使用 lower_bound 来找,参见代码如下:

解法二:

class Solution {
public:
int maxSumSubmatrix(vector<vector<int>>& matrix, int k) {
if (matrix.empty() || matrix[].empty()) return ;
int m = matrix.size(), n = matrix[].size(), res = INT_MIN;
for (int i = ; i < n; ++i) {
vector<int> sum(m);
for (int j = i; j < n; ++j) {
for (int k = ; k < m; ++k) {
sum[k] += matrix[k][j];
}
int curSum = ;
set<int> st{{}};
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 题目讲解汇总(持续更新中...)

[LeetCode] Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K的更多相关文章

  1. Leetcode: 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 s ...

  2. 363. Max Sum of Rectangle No Larger Than K

    /* * 363. Max Sum of Rectangle No Larger Than K * 2016-7-15 by Mingyang */ public int maxSumSubmatri ...

  3. [LeetCode] 363. Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  4. 【LeetCode】363. Max Sum of Rectangle No Larger Than K 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/max-sum- ...

  5. 【leetcode】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 ma ...

  6. 第十三周 Leetcode 363. Max Sum of Rectangle No Larger Than K(HARD)

    Leetcode363 思路: 一种naive的算法就是枚举每个矩形块, 时间复杂度为O((mn)^2), 可以做少许优化时间复杂度可以降低到O(mnnlogm), 其中m为行数, n为列数. 先求出 ...

  7. [Swift]LeetCode363. 矩形区域不超过 K 的最大数值和 | 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 s ...

  8. 363 Max Sum of Rectangle No Larger Than K 最大矩阵和不超过K

    Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...

  9. 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 s ...

随机推荐

  1. ASP.NET MVC 登录验证

     好久没写随笔了,这段时间没 什么事情,领导 一直没安排任务,索性 一直在研究代码,说实在的,这个登录都 搞得我云里雾里的,所以这次我可能也讲得不是 特别清楚,但是 我尽力把我知道的讲出来,顺便也对自 ...

  2. C#6新特性,让你的代码更干净

    前言 前几天看一个朋友的博客时,看他用到了C#6的特性,而6出来这么长时间还没有正儿八经看过它,今儿专门看了下新特性,说白了也不过是语法糖而已.但是用起来确实能让你的代码更加干净些.Let's try ...

  3. 代码的坏味道(10)——发散式变化(Divergent Change)

    坏味道--发散式变化(Divergent Change) 发散式变化(Divergent Change) 类似于 霰弹式修改(Shotgun Surgery) ,但实际上完全不同.发散式变化(Dive ...

  4. 编写高质量代码:改善Java程序的151个建议(第3章:类、对象及方法___建议47~51)

    建议47:在equals中使用getClass进行类型判断 本节我们继续讨论覆写equals的问题,这次我们编写一个员工Employee类继承Person类,这很正常,员工也是人嘛,而且在JavaBe ...

  5. 想着模仿京东微信首页呢,banner滚动搞定了,写到了一半了

    接着上篇 微信小程序-阅读小程序demo写:http://www.cnblogs.com/muyixiaoguang/p/5917986.html 想着模仿京东首页呢,结果也没赶得及写完,轮播图让我搞 ...

  6. Yii 2.x 日志记录器-类图

  7. 居然是Firefox没有抛弃我们

    面向企业级市场,一款网页浏览器的很多特性不是说改就改,说丢弃就丢弃.就像微软不能抛弃IE一样,Firefox也有类似的定位和使命. Firefox即尝试提供企业级市场所需的特性稳定的软件版本(LTS) ...

  8. Scala Macros - scalamela 1.x,inline-meta annotations

    在上期讨论中我们介绍了Scala Macros,它可以说是工具库编程人员不可或缺的编程手段,可以实现编译器在编译源代码时对源代码进行的修改.扩展和替换,如此可以对用户屏蔽工具库复杂的内部细节,使他们可 ...

  9. 开源跨平台IOT通讯框架ServerSuperIO,集成到NuGet程序包管理器,以及Demo使用说明

          物联网涉及到各种设备.各种传感器.各种数据源.各种协议,并且很难统一,那么就要有一个结构性的框架解决这些问题.SSIO就是根据时代发展的阶段和现实实际情况的结合产物. 各种数据信息,如下图 ...

  10. java web学习总结(二十五) -------------------JSP中的九个内置对象

    一.JSP运行原理 每个JSP 页面在第一次被访问时,WEB容器都会把请求交给JSP引擎(即一个Java程序)去处理.JSP引擎先将JSP翻译成一个_jspServlet(实质上也是一个servlet ...