java || dynamic programming
IntuitionApproachComplexity
Time complexity:

Space complexity:
Code
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

# Approach
<!-- Describe your approach to solving the problem. -->

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

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

# Code
```java []
class Solution {
    public int longestSubsequence(int[] nums) {
        int n = nums.length;
        int ans = 2, max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;
        for (int num : nums) {
            max = Math.max(num, max);
            min = Math.min(min, num);
        }
        int[][] dp_pre_num_diff = new int[max + 1][max - min + 1];
        for (int i = n - 1; i >= 0; i--) {
            int num = nums[i];
            int[] curr = new int[max - min + 1];
            int[] dp = dp_pre_num_diff[num];
            for (int diff = 0; diff <= max - min; diff++) {
                curr[diff] = 1;
                int[] targets = new int[]{num - diff, num + diff};
                for (int t : targets) {
                    if (t < min || t > max) continue;
                    int res = 1 + dp_pre_num_diff[t][diff];
                    ans = Math.max(ans, res);
                    curr[diff] = Math.max(curr[diff], res);
                    curr[diff] = Math.max(curr[diff], (diff == 0 ? 0 : curr[diff - 1]));
                }
                dp[diff] = Math.max(dp[diff], curr[diff]);
            }
        }
        return ans;
    }
}
```
['Java']