← Recursion & DP

Micro-Drill #180 — Maximal Square

Recursion & DP Target: 15s

dp[i][j] = side length of largest square with bottom-right at (i,j). min of three neighbors + 1.

def maximalSquare(matrix):
    m, n = len(matrix), len(matrix[0])
    dp = [[0]*n for _ in range(m)]
    res = 0
    for i in range(m):
        for j in range(n):
            if matrix[i][j] == '1':
                if i == 0 or j == 0:
                    dp[i][j] = 1
                else:
                    dp[i][j] = min(dp[i-1][j], dp[i][j-1],
                                   dp[i-1][j-1]) + 1
                res = max(res, dp[i][j])
    return res * res

Type it from memory. Go.

Practice Problems

Related Coding Drills

← Micro #179 Micro #181 →