作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址: https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k/description/

题目描述:

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?

题目大意

找出一个矩阵中的子长方形,使得这个长方形的和是最大的。

解题方法

方法一:暴力求解(TLE)

求和最大的矩形,很容易让人想到先把(0, 0)到所有(i, j)位置的矩形的和求出来,然后再次遍历,求出所有子矩形中和最大的那个。

很无奈,超时了。(好像C++可以通过,python伤不起)

时间复杂度是O((MN)^2),空间复杂度是O(MN)。

class Solution(object):
def maxSumSubmatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
if not matrix or not matrix[0]: return 0
M, N = len(matrix), len(matrix[0])
sums = [[0] * N for _ in range(M)]
res = float("-inf")
for m in range(M):
for n in range(N):
t = matrix[m][n]
if m > 0:
t += sums[m - 1][n]
if n > 0:
t += sums[m][n - 1]
if m > 0 and n > 0:
t -= sums[m - 1][n - 1]
sums[m][n] = t
for r in range(m + 1):
for c in range(n + 1):
d = sums[m][n]
if r > 0:
d -= sums[r - 1][n]
if c > 0:
d -= sums[m][c - 1]
if r > 0 and c > 0:
d += sums[r - 1][c - 1]
if d <= k:
res = max(res, d)
return res

方法二:Kadane’s algorithm (TLE)

看了印度小哥的视频,真的很好理解,告诉我们使用一个数组的情况下,如何找出整个二维子矩阵的最大值。我看了视频之后,写出了这个算法,但是很无奈,直接用这个算法仍然超时。

我分析,这个算法时间复杂度仍然没有降下来,主要问题是获取子数组的最大区间和这一步太耗时了。

时间复杂度是O((MN)^2),空间复杂度是O(M)。

class Solution(object):
def maxSumSubmatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
if not matrix or not matrix[0]: return 0
L, R = 0, 0
curSum, maxSum = float('-inf'), float('-inf')
maxLeft, maxRight, maxUp, maxDown = 0, 0, 0, 0
M, N = len(matrix), len(matrix[0])
for L in range(N):
curArr = [0] * M
for R in range(L, N):
for m in range(M):
curArr[m] += matrix[m][R]
curSum = self.getSumArray(curArr, M, k)
if curSum > maxSum:
maxSum = curSum
return maxSum def getSumArray(self, arr, M, k):
sums = [0] * (M + 1)
for i in range(M):
sums[i + 1] = arr[i] + sums[i]
res = float('-inf')
for i in range(M):
for j in range(i + 1, M + 1):
curSum = sums[j] - sums[i]
if curSum <= k and curSum > res:
res = curSum
return res

方法二:Kadane’s algorithm + 二分查找 (Accepted)

上面的算法慢就慢在查找子数组的最大和部分。其实没必要使用求最大和的方式。因为题目要求我们找出不超过K的和,所以只需要在数组中是否存在另外一个数使得两者的差不超过K即可。这个查找的效率能达到O(NlogN).

在C++中能使用set和lowwer_bound实现,在python中使用bisect_left函数能也实现。

这个过程可以在这个文章中看到更详细的说明。

在时间复杂度中可以看到M影响更大,另外一个优化的策略是重新设置矩形的长和宽,这样也可以优化速度。

时间复杂度是O(MNMlogM),空间复杂度是O(M)。

class Solution(object):
def maxSumSubmatrix(self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
m = len(matrix)
n = len(matrix[0]) if m else 0 M = max(m, n)
N = min(m, n)
ans = None
for x in range(N):
sums = [0] * M
for y in range(x, N):
slist, num = [], 0
for z in range(M):
sums[z] += matrix[z][y] if m > n else matrix[y][z]
num += sums[z]
if num <= k:
ans = max(ans, num)
i = bisect.bisect_left(slist, num - k)
if i != len(slist):
ans = max(ans, num - slist[i])
bisect.insort(slist, num)
return ans or 0

参考资料:

http://bookshadow.com/weblog/2016/06/22/leetcode-max-sum-of-sub-matrix-no-larger-than-k/
http://www.cnblogs.com/grandyang/p/5617660.html
https://www.quora.com/Given-an-array-of-integers-A-and-an-integer-k-find-a-subarray-that-contains-the-largest-sum-subject-to-a-constraint-that-the-sum-is-less-than-k
https://www.youtube.com/watch?v=yCQN096CwWM&t=589s

日期

2018 年 10 月 11 日 —— 做Hard题真的很难

【LeetCode】363. Max Sum of Rectangle No Larger Than K 解题报告(Python)的更多相关文章

  1. [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 ...

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

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

  3. 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 ...

  4. 【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 ...

  5. 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 ...

  6. [LeetCode] 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 ...

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

  8. [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 ...

  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. 【讲座】詹显全——Proteoforms在肿瘤中应用

    Proteoforms/Protein species这个概念还是比较有意义的. 人类结构基因组测序接近尾声,人们就从结构基因组学研究转向功能基因组学研究,即对转录组和蛋白质组进行研究.1995年正式 ...

  2. 分布式事务(4)---最终一致性方案之TCC

    分布式事务(1)-理论基础 分布式事务(2)---强一致性分布式事务解决方案 分布式事务(3)---强一致性分布式事务Atomikos实战 强一致性分布式事务解决方案要求参与事务的各个节点的数据时刻保 ...

  3. 【leetcode】633. Sum of Square Numbers(two-sum 变形)

    Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c. ...

  4. 【swift】长按事件绑定,平移滑动事件+坐标获取

    为何把这两个事件归类在一起? 我后来才明白,iOS有一个手势事件(UiGestureRecognizer) 事件里有7个功能,不过我只试过前两个,也就是标题的这两个(长按.平移滑动) UILongPr ...

  5. C++ 写出这个数

    题目如下: 读入一个正整数 n,计算其各位数字之和,用汉语拼音写出和的每一位数字. 输入格式: 每个测试输入包含 1 个测试用例,即给出自然数 n 的值.这里保证 n 小于 1. 输出格式: 在一行内 ...

  6. SpringBoot(4):整合Mybatis

    1. 导入mybatis所需要的依赖 1 <!-- 引入 myBatis,这是 MyBatis官方提供的适配 Spring Boot的--> 2 <dependency> 3 ...

  7. 基于war的Spring Boot工程

    一.简介 前面创建的Spring Boot工程最终被打为了Jar包,是以可执行文件的形式出现的,其使用了Spring Boot内嵌的Tomcat作为Web服务器来运行web应用的.新版Dubbo的监控 ...

  8. 【Python】数据处理分析,一些问题记录

    不用造轮子是真的好用啊 python中单引号双引号的区别 和cpp不一样,cpp单引号表示字符,双引号表示字符串,'c'就直接是ascii值了 Python中单引号和双引号都可以用来表示一个字符串 单 ...

  9. 【MySQL】亲测可用的教程筛选:安装与卸载

    windows版本的 安装看这篇,非常详细:https://www.cnblogs.com/winton-nfs/p/11524007.html 彻底清除:https://www.pianshen.c ...

  10. 云原生时代之Kubernetes容器编排初步探索及部署、使用实战-v1.22

    概述 **本人博客网站 **IT小神 www.itxiaoshen.com Kubernetes官网地址 https://kubernetes.io Kubernetes GitHub源码地址 htt ...