Maximum Side Length of a Square with Sum Less than or Equal to Threshold - Problem
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.
A square is defined as a submatrix where all sides have equal length. The sum of a square is the sum of all elements within that submatrix.
Input & Output
Example 1 — Basic Case
$
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
💡 Note:
The maximum side-length of a square with sum ≤ 4 is 2. The 2×2 square at position (0,0) has sum = 1+1+1+1 = 4.
Example 2 — Larger Threshold
$
Input:
mat = [[2,2,2,2,5,5],[2,2,2,2,5,5],[2,2,2,2,5,5],[2,2,2,2,5,5]], threshold = 18
›
Output:
2
💡 Note:
A 2×2 square of all 2's has sum = 8 ≤ 18. A 3×3 square would have sum ≥ 18, but we need strictly ≤ threshold.
Example 3 — No Valid Square
$
Input:
mat = [[1,1,1,1],[1,1,1,1],[1,1,1,1]], threshold = 0
›
Output:
0
💡 Note:
Even the smallest 1×1 square has sum = 1 > 0, so no valid square exists.
Constraints
- 1 ≤ m, n ≤ 300
- 0 ≤ mat[i][j] ≤ 104
- 0 ≤ threshold ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code