Detailed DP Solution
Complexity
Time complexity: O(n*300)

Space complexity: O(300*300)
Code

# Complexity
- Time complexity: O(n*300)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->

- Space complexity: O(300*300)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```cpp []
class Solution {
public:
    int longestSubsequence(vector<int>& nums) {
        int n = nums.size();
        int ans = 2;

        int dp[305][305]; //currNum, diff -> max len of subseq ending with currNum and having diffenence equal to diff
        int mx[305][305]; //last, diff -> maxlen of subseq ending with last and having difference greater than diff
        memset(dp, -1, sizeof(dp));
        memset(mx, -1, sizeof(mx));

        for(auto num : nums){
            if(dp[num][0] < 1) dp[num][0] = 1;

            for(int prev=1; prev<=300; prev++){
                int currDiff = abs(num-prev);
                int mxLen = mx[prev][currDiff];

                if(mxLen>1){
                    dp[num][currDiff] = max(dp[num][currDiff], 1 + mxLen);
                }
                else{
                    if(mx[prev][0] > 0) dp[num][currDiff] = max(dp[num][currDiff], 2); // new subseq but prev num should exist
                }

                ans = max(ans, dp[num][currDiff]);
            }

            mx[num][299] = dp[num][299];
            for(int i=298;i>=0;i--){
                mx[num][i] = max(dp[num][i], mx[num][i+1]);
            }
        }

        return ans;
    }
};
```
['C++']