<p>Given an integer array <code>arr</code> and an integer <code>difference</code>, return the length of the longest subsequence in <code>arr</code> which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals <code>difference</code>.</p>

<p>A <strong>subsequence</strong> is a sequence that can be derived from <code>arr</code> by deleting some or no elements without changing the order of the remaining elements.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> arr = [1,2,3,4], difference = 1
<strong>Output:</strong> 4
<strong>Explanation: </strong>The longest arithmetic subsequence is [1,2,3,4].</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> arr = [1,3,5,7], difference = 1
<strong>Output:</strong> 1
<strong>Explanation: </strong>The longest arithmetic subsequence is any single element.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> arr = [1,5,7,8,5,3,4,2,1], difference = -2
<strong>Output:</strong> 4
<strong>Explanation: </strong>The longest arithmetic subsequence is [7,5,3,1].
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= arr.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= arr[i], difference &lt;= 10<sup>4</sup></code></li>
</ul>

class Solution:
    def longestSubsequence(self, arr: List[int], d: int) -> int:
        return sol3(arr, d)

def sol1(nums, k):
    N = len(nums)
    K = k 
    INF =  10**10

    @cache
    def dfs(i, prev):
        if(i >= len(nums)): return 0
        take, ignore = 0, 0
        if prev == None or nums[i] - prev == K: take = 1 + dfs(i+1, nums[i])
        ignore = dfs(i+1, prev)
        #print(ignore)
        return max(ignore, take)
    return dfs(0, None)

def sol2(nums, K):
    N = len(nums)

    @cache
    def dfs(idx, state, prev):
        if idx == N: return 0
        if state and (prev == None or nums[idx]-prev == K): return 1 + dfs(idx+1, 1, nums[idx])
        if state: return 0 + dfs(idx+1, 1, prev)
        return max(
            dfs(idx+1, 0, prev),
            1 + dfs(idx+1, 1, nums[idx])
        )
    return dfs(0,0,None)


def sol3(nums, K):
    max_length, dp = 0, defaultdict(int)
    for i in range(len(nums)):
        dp[nums[i]] = 1 + dp[nums[i]-K]
        max_length = max(max_length, dp[nums[i]])
    return max_length

29800