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

Difficulty: interview

Starter code:

class Solution:
    def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
        

Solutions:
class Solution:
    def maxSideLength(self, mat: List[List[int]], threshold: int) -> int:
        dp = [[0 for _ in range(len(mat[0]) + 1)]for r in range(len(mat) + 1)]
        
        for r in range(1, len(mat) + 1):
            for c in range(1, len(mat[r-1]) + 1):
                dp[r][c] += mat[r-1][c-1]
                if not r and not c:
                    continue
                elif not r:
                    dp[r][c] += dp[r][c-1]
                    continue
                elif not c:
                    dp[r][c] += dp[r-1][c]
                    continue
                dp[r][c] += dp[r][c-1] + dp[r-1][c] - dp[r-1][c-1]
         
        # print(dp)
        highest = -1
        for r in range(1, len(dp)):
            r0= r1 = r
            c0= c1 = 1
            while r1 < len(dp) and c1 < len(dp[0]):
              
                result = dp[r1][c1] + dp[r0-1][c0-1] - dp[r1][c0-1] - dp[r0-1][c1]
  
                # print(f'r0:{r0} r1:{r1} c0:{c0} c1:{c1} result:{result}')
                if result <= threshold:
                    highest = max(r1-r0, highest)
                    r1 += 1
                    c1 +=1
                else:
                    r1 -=1
                    c0 +=1
                r1 = max(r0+1,r1)
                c1 = max(c0+1,c1)

        return highest + 1