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 or equal to 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
Solutions
Solution 1: 2D Prefix Sum + Binary Search
Thinking
A square's sum grows with its side (entries are non-negative), so feasibility is monotone. \(m,n \le 300\); enumerating sides and corners with an \(O(k^2)\) sum is too slow. A 2-D prefix makes every square \(O(1)\), and we binary-search the side.
The check scans top-left corners and compares the prefix sum to the threshold. The search returns the largest feasible side.
We can precompute a 2D prefix sum array \(s\), where \(s[i + 1][j + 1]\) represents the sum of elements in the matrix \(mat\) from \((0, 0)\) to \((i, j)\). With this, we can calculate the sum of elements in any square region in \(O(1)\) time.
Next, we can use binary search to find the maximum side length. We enumerate the side length \(k\) of the square, and then iterate through all possible top-left positions \((i, j)\) of the square. We can calculate the sum of elements \(v\) for the square. If \(v \leq threshold\), it indicates that there exists a square region with side length \(k\) whose sum is less than or equal to the threshold; otherwise, no such square exists for the current \(k\).
The time complexity is \(O(m \times n \times \log \min(m, n))\), and the space complexity is \(O(m \times n)\).