[Swift]LeetCode363. 矩形區域不超過 K 的最大數值和 | Max Sum of Rectangle No Larger Than K

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-wqwrixzh-ga.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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.git

Example:github

Input: matrix = [[1,0,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, 1], [-2, 3]]

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?

給定一個非空二維矩陣 matrix 和一個整數 k,找到這個矩陣內部不大於 k的最大矩形和。ide

示例:spa

輸入: matrix = [[1,0,1],[0,-2,3]], k = 2
輸出: 2 
解釋: 矩形區域  的數值和是 2,且 2 是不超過 k 的最大數字(k = 2)。
[[0, 1], [-2, 3]]

說明:code

  1. 矩陣內的矩形區域面積必須大於 0。
  2. 若是行數遠大於列數,你將如何解答呢?

13108mshtm

 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 }
相關文章
相關標籤/搜索