LeetCode 题解工作台
矩形区域不超过 K 的最大数值和
给你一个 m x n 的矩阵 matrix 和一个整数 k ,找出并返回矩阵内部矩形区域的不超过 k 的最大数值和。 题目数据保证总会存在一个数值和不超过 k 的矩形区域。 示例 1: 输入: matrix = [[1,0,1],[0,-2,3]], k = 2 输出: 2 解释: 蓝色边框圈出来的…
5
题型
5
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
答案摘要
我们可以枚举矩形的上下边界 和 ,然后计算出该边界内每列的元素和,记录在数组 中,问题转化为如何在数组 中寻找不超过 的最大子数组和。 我们可以使用有序集合来快速寻找小于等于 的最大值,从而得到最大子数组和不超过 的子数组。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
给你一个 m x n 的矩阵 matrix 和一个整数 k ,找出并返回矩阵内部矩形区域的不超过 k 的最大数值和。
题目数据保证总会存在一个数值和不超过 k 的矩形区域。
示例 1:
输入:matrix = [[1,0,1],[0,-2,3]], k = 2
输出:2
解释:蓝色边框圈出来的矩形区域 [[0, 1], [-2, 3]] 的数值和是 2,且 2 是不超过 k 的最大数字(k = 2)。
示例 2:
输入:matrix = [[2,2,-1]], k = 3 输出:3
提示:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 100-100 <= matrix[i][j] <= 100-105 <= k <= 105
进阶:如果行数远大于列数,该如何设计解决方案?
解题思路
方法一:枚举边界 + 有序集合
我们可以枚举矩形的上下边界 和 ,然后计算出该边界内每列的元素和,记录在数组 中,问题转化为如何在数组 中寻找不超过 的最大子数组和。
我们可以使用有序集合来快速寻找小于等于 的最大值,从而得到最大子数组和不超过 的子数组。
时间复杂度 ,空间复杂度 。
class Solution:
def maxSumSubmatrix(self, matrix: List[List[int]], k: int) -> int:
m, n = len(matrix), len(matrix[0])
ans = -inf
for i in range(m):
nums = [0] * n
for j in range(i, m):
for h in range(n):
nums[h] += matrix[j][h]
s = 0
ts = SortedSet([0])
for x in nums:
s += x
p = ts.bisect_left(s - k)
if p != len(ts):
ans = max(ans, s - ts[p])
ts.add(s)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the binary search and matrix operations. In the worst case, the solution may involve iterating through rows and columns, leading to a time complexity of O(n^2 log k). Space complexity is influenced by the need to store prefix sums and ordered sets, resulting in O(n^2) space. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Ability to efficiently handle a dynamic programming problem with constraints.
- question_mark
Skill in optimizing matrix-based solutions with space and time complexity considerations.
- question_mark
Proficiency in using binary search and ordered data structures for algorithmic optimization.
常见陷阱
外企场景- error
Failing to correctly implement the binary search to narrow down valid sums.
- error
Neglecting to optimize sum calculations using prefix sums, leading to inefficient solutions.
- error
Improper handling of edge cases, such as when k is very small or the matrix contains negative values.
进阶变体
外企场景- arrow_right_alt
Max Sum of Submatrix with Exact Sum: Instead of maximizing the sum, the goal is to find a submatrix with a sum equal to k.
- arrow_right_alt
Max Sum of Rectangle No Larger Than K with Multiple Queries: Handling multiple k values for the same matrix and optimizing for each query.
- arrow_right_alt
Max Sum of Subrectangle in a 2D Matrix with Larger k: An extension where k is larger, requiring different search space handling.