132 ms !!! 2D DP approach with O(n * (300 + 300)) = O(n) Linear Time Complexity
IntuitionApproachComplexity
Time complexity: O(n∗(maxvalue+maxvalue))=O(n∗(300+300))=  O(n)

Space complexity:O((maxvalue+2)∗(maxvalue+2))= O(302∗302)=   O(1)
C
# Intuition
<!-- Describe your first thoughts on how to solve this problem. -->

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

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

- Space complexity:$$O((maxvalue + 2) * (maxvalue + 2)) =$$ $$O(302 * 302)= $$   $$O(1)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->

# Code
```java []
class Solution {
    public int longestSubsequence(int[] nums) {
         // Create a 2D array for dynamic programming
        int[][] dp = new int[302][302];
        
        // Iterate through the array from right to left
        for (int i = nums.length - 1; i >= 0; --i) {
            int num = nums[i];
            
            // For each possible next number
            for (int next = 1; next <= 300; ++next) {
                int diff = Math.abs(next - num);
                dp[num][diff] = Math.max(dp[num][diff], dp[next][diff] + 1);
            }
            
            // Update dp values for current number
            for (int j = 1; j <= 300; ++j) {
                dp[num][j] = Math.max(dp[num][j], dp[num][j - 1]);
            }
        }
        
        // Find the maximum value in dp array
        int ans = Integer.MIN_VALUE;
        for (int i = 0; i <= 301; ++i) {
            for (int j = 0; j <= 301; ++j) {
                ans = Math.max(ans, dp[i][j]);
            }
        }
        
        return ans;
    }
}
```
['Dynamic Programming', 'Java']