[Swift]LeetCode363. 矩形区域不超过 K 的最大数值和 | Max Sum of Rectangle No Larger Than K
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/10277610.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
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:
- The rectangle inside the matrix must have an area > 0.
- What if the number of rows is much larger than the number of columns?
给定一个非空二维矩阵 matrix 和一个整数 k,找到这个矩阵内部不大于 k的最大矩形和。
示例:
输入: matrix = [[1,0,1],[0,-2,3]], k = 2
输出: 2
解释: 矩形区域 [[0, 1], [-2, 3]]
的数值和是 2,且 2 是不超过 k 的最大数字(k = 2)。
说明:
- 矩阵内的矩形区域面积必须大于 0。
- 如果行数远大于列数,你将如何解答呢?
13108ms
1 class Solution { 2 func maxSumSubmatrix(_ matrix: [[Int]], _ k: Int) -> Int { 3 if matrix.isEmpty || matrix[0].isEmpty {return 0} 4 var m:Int = matrix.count 5 var n:Int = matrix[0].count 6 var res:Int = Int.min 7 var sum:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:n),count:m) 8 for i in 0..<m 9 { 10 for j in 0..<n 11 { 12 var t:Int = matrix[i][j] 13 if i > 0 {t += sum[i - 1][j]} 14 if j > 0 {t += sum[i][j - 1]} 15 if i > 0 && j > 0 {t -= sum[i - 1][j - 1]} 16 sum[i][j] = t 17 for r in 0...i 18 { 19 for c in 0...j 20 { 21 var d:Int = sum[i][j] 22 if r > 0 {d -= sum[r - 1][j]} 23 if c > 0 {d -= sum[i][c - 1]} 24 if r > 0 && c > 0 {d += sum[r - 1][c - 1]} 25 if d <= k {res = max(res, d)} 26 } 27 } 28 } 29 } 30 return res 31 } 32 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了