```python
def lps(str):
    n = len(str)

    if n <= 1:
        return n

    # dp_table[i][j] stores the length of the longest palindromic subsequence
    # in the substring str[i...j].
    dp_table = [[0 for _ in range(n)] for _ in range(n)]

    # Every single character is a palindrome of length 1.
    for i in range(n):
        dp_table[i][i] = 1

    # We fill the table for substrings of increasing length, from 2 to n.
    # 'sub_len' is the length of the substring being considered.
    for sub_len in range(2, n + 1):
        # 'start' is the starting index of the substring.
        for start in range(n - sub_len + 1):
            end = start + sub_len - 1
            
            # Case 1: The characters at the ends of the substring match.
            if str[start] == str[end]:
                # The two matching end characters add 2 to the length.
                # The rest is the LPS of the inner substring.
                dp_table[start][end] = 2 + dp_table[start + 1][end - 1]
            # Case 2: The characters at the ends do not match.
            else:
                # We must discard one of the end characters. We take the maximum
                # length from the two possibilities (excluding the start or the end).
                lps_without_start = dp_table[start + 1][end]
                lps_without_end = dp_table[start][end - 1]
                dp_table[start][end] = max(lps_without_start, lps_without_end)

    # The final answer is the LPS of the entire string (from index 0 to n-1).
    return dp_table[0][n - 1]
```