Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 516 Longest Palindromic Subsequence - Key Observation

Endpoints determine structure

Focus on the endpoints of your current range [i,j][i, j]. If s[i]=s[j]s[i] = s[j]: both characters can be endpoints of a palindrome. The remaining problem is finding the LPS in s[i+1..j1]s[i+1..j-1], then adding 22 for these matching endpoints.

If s[i]s[j]s[i] \neq s[j]: at least one endpoint must be excluded. Either skip s[i]s[i] (solve s[i+1..j]s[i+1..j]) or skip s[j]s[j] (solve s[i..j1]s[i..j-1]). Take the maximum. This gives us a clean two-case recurrence with no need to try all split points.