Leetcode 516 Solution

This article provides solution to leetcode question 516 (longest-palindromic-subsequence)

https://leetcode.com/problems/longest-palindromic-subsequence

Solution

class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        n = len(s)
        dp = [[0 for _ in range(n)] for _ in range(n)]

        for i in range(n):
            dp[i][i] = 1

        for k in range(1, n):
            for i in range(n - k):
                j = i + k

                if s[i] == s[j]:
                    dp[i][j] = dp[i + 1][j - 1] + 2
                else:
                    dp[i][j] = max(dp[i][j - 1], dp[i + 1][j])

        return dp[0][-1]