Max Palindromic Subsequence

Max Palindromic Subsequence

Return the length of the longest subsequence of s that is a palindrome. A subsequence keeps order but may drop characters.

maxPalindromicSubsequence(s)

Input format: a single string.

Examples

"luwxult"   // → 5   ("luxul")
"xyxz"      // → 3   ("xyx")
"a"         // → 1

Walkthrough

Thinking in terms of shrinking ranges

A palindrome's first and last characters must match, which points to defining the subproblem on a range [i, j] rather than a prefix or single index. Ask: what's the longest palindromic subsequence within that range?

If the end characters match, both can be in the palindrome (one at each end), contributing 2, plus whatever palindrome fits strictly between them: 2 + best(i+1, j-1). If they differ, at least one can't be an outer pair for the whole range, so take the better of dropping the left end or the right: max(best(i+1, j), best(i, j-1)).

Base cases

A single character is a palindrome of length 1. A range where left has passed right (empty) contributes 0.

Why the naive recursion is expensive

Many different sequences of "drop left" / "drop right" decisions land on the same (i, j) range. The naive approach recomputes the best length for that range every time, even though the answer never changes. This grows exponentially with string length.

The subproblem: an interval

The best length for a range depends only on its endpoints i and j — not on how the recursion narrowed to it. This is interval DP: the state is a contiguous interval, and larger intervals build from smaller nested ones.

Cache keyed by (i, j). Check before recursing; otherwise apply the match/mismatch logic, store, return.

Complexity payoff

O(n²) distinct (i, j) pairs for a string of length n, each computed once at constant cost given cached sub-ranges — O(n²) total instead of exponential. Interval DP reappears whenever a problem's structure depends on matching or splitting a contiguous stretch.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.