Explained: Simple and clean c++ solution in O(N*M) time, O(M^2) memory
IntuitionUsing index of nums in dp state is going to produce unmanagable state considering time/memory constaints, so we have to figure out more efficient state
# Intuition
Using index of nums in dp state is going to produce unmanagable state considering time/memory constaints, so we have to figure out more efficient state.
If we thought it through, we actually can solve for `num` and `diff` for a sub array and then incrementally build the higher level states using it.

# Approach
Explained in comments in the code.

# Complexity
- Time complexity:
$$O(N*M)$$ 

- Space complexity:
$$O(M^2)$$ 

# Code
```cpp []
class Solution {
public:
    int longestSubsequence(vector<int>& nums) {
        const int N = nums.size();
        const int M = 303;
        vector<vector<int>> dp(M, vector<int>(M, 0));
        for(int num : nums) {
            for(int prev = 1; prev <= 300; prev++) {
                int diff = abs(num - prev);
                dp[num][diff] = max(dp[num][diff], 1 + dp[prev][diff]);
            }
            for(int diff = 300; diff >= 0; diff--) {
                dp[num][diff] = max(dp[num][diff], dp[num][diff + 1]);
            }
        }
        // Let dp[num][some_diff] be the length of longest subsequence ending with number `num`, and having `some_diff` as the last/smallest absolute difference `diff` between `num` and previous element `prev`
        // So, for each `num`, for all possible numbers `prev` to `num`:
        //      let diff = |num - prev| and
        //      dp[num][some_diff] = max of all {1 + dp[prev][diff] ..} such that diff >= some_diff >= 0
        // Instead of updating one by one dp[num][some_diff] for all valid values of `some_diff` for each `diff`,
        // We calculate the dp[num][diff] value once per `diff`, Then maximize all dp[num][sum_diff] by dp[num][dif] for all some_diff <= diff,
        // We do that maximization in the last inner loop above.
        int ans = 0;
        for(int num = 1; num <= 300; num++) {
            for(int diff = 0; diff <= 300; diff++) {
                ans = max(ans, dp[num][diff]);
            }
        }
        return ans;
    }
};
```
['C++']