[C++] DP

```cpp []
const int       N = 10 + 1e3;
const int       T = 300;

class Solution {
public:
    int longestSubsequence(vector<int>& nums) {  
        int cnt[N];
        memset(cnt, 0, sizeof(cnt));
        for (auto val : nums) cnt[val]++;

        int f[N][N];
        memset(f, 0, sizeof(f));
        for (auto u : nums) f[u][T] = 1;
        for (auto u : nums) {                       int upp = 0;                cnt[u]--;
            for (int w = T; w >= 0; w--) {          int a = u-w, b = u+w;       upp = max(upp, f[u][w]);
                if (1 <= a && a <= T && cnt[a]) f[a][w] = max(f[a][w], upp + 1);
                if (1 <= b && b <= T && cnt[b]) f[b][w] = max(f[b][w], upp + 1);
            }
        }

        int ans = 0;
        for (auto u : nums) {
            for (int w = 0; w <= T; w++) ans = max(ans, f[u][w]);
        }
        return ans;
    }
};


```
['C++']