Talentd
FleetCode

1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold

Medium65.4% acceptance4 companies

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

Constraints:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 300
  • 0 <= mat[i][j] <= 104
  • 0 <= threshold <= 105

Hints open one at a time

Hint 1
Store prefix sum of all grids in another 2D array.
Hint 2
Try all possible solutions and if you cannot find one return -1.
Hint 3
If x is a valid answer then any y < x is also valid answer. Use binary search to find answer.
1:01:20
Still stuck?Read 3 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
3
Starter codePython 3Spaces: 4
Examples
Input
[[1,1,3,2,4,3,2],[1,1,3,2,4,3,2],[1,1,3,2,4,3,2]]
4
Input
[[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]]
1
Your code is saved on this device.Solution