C++ optimized solution 
Complexity
Time complexity:O(N*maxNumber)

Space complexity:O(maxNumber*maxNumber)
Code


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

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

# Code
```cpp []
class Solution {
    int prefdp[301][301]={0};
public:
    int longestSubsequence(vector<int>& nums) {
        int n = nums.size();
        unordered_set<int> st;
        int maxn = *max_element(nums.begin(), nums.end());
        for (int i = 0; i <= maxn; i++) {
            // dp[nums[0]][i] = 1;
            prefdp[nums[0]][i]=1;
        }
        st.insert(nums[0]);
        int cnt = 1;
        
        for (int i = 1; i < n; i++) {
            int x = nums[i];
            int ch = 0;
            // vector<int>ds(maxn+1,0);
            int pmaxi=0;
            if (st.find(x) == st.end())
                ch = 1;
            for (int j=maxn;j>=0;j--) {
                int cans=0;
                if (ch == 1)
                    cans = 1;

                int t = x + j;
                if (st.find(x + j) != st.end()) {
                    int maxi = 0;
                    maxi=max(maxi,prefdp[t][j]);
                    cans = max(cans, 1 + maxi);
                }
                t = x - j;
                if (st.find(x - j) != st.end()) {

                    int maxi = 0;
                    maxi=max(maxi,prefdp[t][j]);

                    cans = max(cans, 1 + maxi);
                }
                pmaxi=max(pmaxi,cans);
                 prefdp[x][j]=max(pmaxi,prefdp[x][j]);
                cnt = max(cnt, prefdp[x][j]);
            }
            st.insert(x);
        }

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