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,1],[0,-2,3]],k = 2 Output: 2 Explanation: Because the sum of rectangle is 2, and 2 is the max number no larger than k (k = 2).[[0,[-2,3]]
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,k = 2输出: 2 解释: 矩形区域 的数值和是 2,且 2 是不超过 k 的最大数字(k = 2)。[[0,3]]
说明:
矩阵内的矩形区域面积必须大于 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..<n11 {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] = t17 for r in 0...i18 {19 for c in 0...j20 {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 res31 }32 }总结
以上是内存溢出为你收集整理的[Swift]LeetCode363. 矩形区域不超过 K 的最大数值和 | Max Sum of Rectangle No Larger Than K全部内容,希望文章能够帮你解决[Swift]LeetCode363. 矩形区域不超过 K 的最大数值和 | Max Sum of Rectangle No Larger Than K所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)