[Swift]LeetCode1183. 矩陣中 1 的最大數量 | Maximum Number of Ones


★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公眾號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(www.zengqiang.org
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/11484247.html
➤如果鏈接不是山青詠芝的博客園地址,則可能是爬取作者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持作者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

Consider a matrix M with dimensions width * height, such that every cell has value 0 or 1, and any square sub-matrix of M of size sideLength * sideLength has at most maxOnes ones.

Return the maximum possible number of ones that the matrix M can have.

 

Example 1:

Input: width = 3, height = 3, sideLength = 2, maxOnes = 1
Output: 4
Explanation:
In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one.
The best solution that has 4 ones is:
[1,0,1]
[0,0,0]
[1,0,1]

Example 2:

Input: width = 3, height = 3, sideLength = 2, maxOnes = 2
Output: 6
Explanation:
[1,0,1]
[1,0,1]
[1,0,1]

 

Constraints:

  • 1 <= width, height <= 100
  • 1 <= sideLength <= width, height
  • 0 <= maxOnes <= sideLength * sideLength

 

現在有一個尺寸為 width * height 的矩陣 M,矩陣中的每個單元格的值不是 0 就是 1

而且矩陣 M 中每個大小為 sideLength * sideLength 的 正方形 子陣中,1 的數量不得超過 maxOnes

請你設計一個算法,計算矩陣中最多可以有多少個 1

 

示例 1:

輸入:width = 3, height = 3, sideLength = 2, maxOnes = 1
輸出:4
解釋:
題目要求:在一個 3*3 的矩陣中,每一個 2*2 的子陣中的 1 的數目不超過 1 個。
最好的解決方案中,矩陣 M 里最多可以有 4 個 1,如下所示:
[1,0,1]
[0,0,0]
[1,0,1]

示例 2:

輸入:width = 3, height = 3, sideLength = 2, maxOnes = 2
輸出:6
解釋:
[1,0,1]
[1,0,1]
[1,0,1]

 

提示:

  • 1 <= width, height <= 100
  • 1 <= sideLength <= width, height
  • 0 <= maxOnes <= sideLength * sideLength

Runtime: 32 ms
Memory Usage: 21 MB
 1 class Solution {
 2     func maximumNumberOfOnes(_ width: Int, _ height: Int, _ sideLength: Int, _ maxOnes: Int) -> Int {
 3         var res:[Int] = [Int]()
 4         for i in 0..<sideLength
 5         {
 6             for j in 0..<sideLength
 7             {
 8                 res.append(((width-i-1)/sideLength+1)*((height-j-1)/sideLength+1))
 9             }
10         }
11         res = res.sorted(by:>)
12         var ans:Int = 0
13         for i in 0..<maxOnes
14         {
15             ans += res[i]
16         }
17         return ans
18     }
19 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM