1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold
程序员文章站
2024-03-06 21:52:02
...
Given a m x n
matrix mat
and an integer threshold
. Return the maximum side-length of a square with a sum less than or equal to threshold
or return 0 if there is no such square.
Example 1:
Input: mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4 Output: 2 Explanation: The maximum side length of square with sum less than 4 is 2 as shown.
Example 2:
Input: mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1 Output: 0
Example 3:
Input: mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6 Output: 3
Example 4:
Input: mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184 Output: 2
Constraints:
1 <= m, n <= 300
m == mat.length
n == mat[i].length
0 <= mat[i][j] <= 10000
0 <= threshold <= 10^5
思路:DP+二分
class Solution(object):
def maxSideLength(self, mat, threshold):
"""
:type mat: List[List[int]]
:type threshold: int
:rtype: int
"""
import math
m,n = len(mat),len(mat[0])
dp = [[0 for _ in range(n+1)] for _ in range(m+1)]
for i in range(1,m+1):
for j in range(1,n+1):
dp[i][j]=dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]+mat[i-1][j-1]
def ok(res):
for i in range(res,m+1):
for j in range(res,n+1):
t = dp[i][j]-dp[i][j-res]-dp[i-res][j]+dp[i-res][j-res]
if t<=threshold: return True
return False
lo,hi = 0,min(m,n)
res = 0
while lo<=hi:
mid=(lo+hi)//2
if ok(mid):
res = max(res,mid)
lo=mid+1
else:
hi=mid-1
return res
s=Solution()
print(s.maxSideLength(mat = [[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]], threshold = 4))
print(s.maxSideLength(mat = [[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2],[2,2,2,2,2]], threshold = 1))
print(s.maxSideLength(mat = [[1,1,1,1],[1,0,0,0],[1,0,0,0],[1,0,0,0]], threshold = 6))
print(s.maxSideLength(mat = [[18,70],[61,1],[25,85],[14,40],[11,96],[97,96],[63,45]], threshold = 40184))
上一篇: 循环链表的C风格实现(单向)
下一篇: Android如何创建桌面快捷方式
推荐阅读
-
1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold
-
LeetCode-1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold
-
[leetcode] 1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold
-
Maximum Side Length of a Square with Sum Less than or Equal to Threshold