1. Recurrence
if A[i-1] == B[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
Derivation of recurrence, reconstruction, space reductions, and classic variants.
dp[i][j] length LCS of prefixes
Match → diag+1 else max(up,left)
Keep 2 rows
if A[i-1] == B[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
Start bottom-right, move diagonally on match, else move to the larger predecessor.