```python
def lps(str):
    n = len(str)
    if n == 0:
        return 0

    # dp[i][j] will store the length of the longest palindromic subsequence
    # in the substring str[i..j]
    dp = [[0] * n for _ in range(n)]

    # Iterate through the string characters from the end to the beginning
    for i in range(n - 1, -1, -1):
        # Base case: every single character is a palindrome of length 1
        dp[i][i] = 1
        # j starts from i+1
        for j in range(i + 1, n):
            # If characters at both ends are the same
            if str[i] == str[j]:
                dp[i][j] = 2 + dp[i+1][j-1]
            # If characters at both ends are different
            else:
                dp[i][j] = max(dp[i+1][j], dp[i][j-1])

    return dp[0][n-1]
```