# 516. Longest Palindromic Subsequence

```
TC: O(n^2)
SC: O(n^2)
```

```java
class Solution {
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        
        for (int i = 0; i < n; i++) {
            dp[i][i] = 1;
        }
        for (int i = n-1; i >= 0; i--) {
            for (int j = i+1; j < n; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i+1][j-1] + 2;
                } else {
                    dp[i][j] = Math.max(dp[i][j-1], dp[i+1][j]);
                }
            }
        }
        return dp[0][n-1];
    }
}
/*

Longest Palindromic Subsequence


dp[i][j]: Longest Palindromic Subsequence for s[i:j]

i xxxxxx j

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])


s[i] != s[j] so we can't have i, j at the same time
[       ]
i xxxxxx j
  [      ]
  
base case, if i == j , value is 1 (only one character)
if (i < j ) value is all 0

[i, j-1]   [i,j]
[i+1, j-1] [i+1, j]

      j
      -> ->
   1  x. x  ^
i  0  1  x  |
   0  0  1   for right buttom to exe

TC: O(n^2)
SC: O(n^2)

*/
```

## DFS + MEMO

````java
```java
class Solution {
    public int longestPalindromeSubseq(String s) {
        int n = s.length();
        Integer[][] memo = new Integer[n][n];
        return dfs(0, n-1, s, memo);
    }
    private int dfs(int i, int j, String s, Integer[][] memo) {
        if (i > j) {
            return 0;
        }
        if (i == j) { // when s = "a"
            return 1;
        }
        if (memo[i][j] != null) {
            return memo[i][j];
        }
        if (s.charAt(i) == s.charAt(j)) {
            return memo[i][j] = dfs(i+1, j-1, s, memo) + 2;
        } else {
            return memo[i][j] = Math.max(dfs(i+1, j, s, memo), dfs(i, j-1, s, memo));
        }
    }
}

/*
begin and end same -> 

b bba b

dfs(bbbab)
same -> dfs(bba) + 2 ...

dfs(cbbd)
not same  -> max(dfs(bbd), dfs(cbb)) ...

if s[0] == s[n] -> dfs(i+1, j-1) + 2
if s[0] != s[n] -> max(dfs(i+1, j) , dfs(i, j-1))

T: O(n^2)
T: O(n^2)
*/
```
````


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/dynamic-programming/qu-jian-dp/516.-longest-palindromic-subsequence.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
