C++ | DP
IntuitionWe find for each element the longest subsequence possible for particular difference d, dp[i][j] denotes longest subsequence possible for element i for
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
We find for each element the longest subsequence possible for particular difference $$d$$, $$dp[i][j]$$ denotes longest subsequence possible for element $$i$$ for particular difference $$d$$ with previous element and use that previous element to use the dynamic programming.


# Complexity
$$mx$$ = max element in array
- Time complexity: $$O(n*mx)$$
 


- Space complexity: $$O(mx*mx)$$

# Code
```cpp []
class Solution {
public:
    int longestSubsequence(vector<int>& v) {
        int n = v.size();
        int mx = *max_element(v.begin(),v.end());
        
        vector<vector<int>>dp(mx+1,vector<int>(mx+2,0));
        int ans = 2;
        for(auto i:v){
            for(int d = mx;d>=0;d--){

                if(i+d<=mx) dp[i][d] = max(dp[i][d],1+dp[i+d][d]);
                if(i>=d && d!=0) dp[i][d] = max(dp[i][d],1+dp[i-d][d]);
                
                dp[i][d] = max(dp[i][d],dp[i][d+1]);
                ans = max(ans,dp[i][d]);
                
            }
        }
        return ans;
    }
};
```
['C++']