human
Solve in Python:
Given an integer array arr and an integer difference, return the length of the longest subsequence in arr which is an arithmetic sequence such that the difference between adjacent elements in the subsequence equals difference.
 
Example 1:
Input: arr = [1,2,3,4], difference = 1
Output: 4
Explanation: The longest arithmetic subsequence is [1,2,3,4].
Example 2:
Input: arr = [1,3,5,7], difference = 1
Output: 1
Explanation: The longest arithmetic subsequence is any single element.

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

 
Constraints:

1 <= arr.length <= 10^5
-10^4 <= arr[i], difference <= 10^4
assistant
#Here is the Python code you requested.

from collections import defaultdict
class Solution:
    # 先写出brute force solution O(n^2)，在下面
    # 再尝试用dp优化 
    def longestSubsequence(self, arr: List[int], difference: int) -> int:
        n = len(arr)
        ret = 0
        
        mappings = defaultdict(list)
        for i, v in enumerate(arr):
            mappings[v].append(i)
            
        M = [-1 for i in range(n)]
        
        def dp(i):
            if i == n-1:
                return 1
            
            if M[i] != -1:
                return M[i]
            
            M[i] = 1
            for j in mappings[arr[i]+difference]:
                if j > i:
                    M[i] += dp(j)
                    break
            
            return M[i]
        
        for i in range(n):
            ret = max(ret, dp(i))
            
        return ret
    
    
#     def longestSubsequence(self, arr: List[int], difference: int) -> int:
#         n = len(arr)
#         ret = 0
        
#         for i, num in enumerate(arr):
#             cur = num
#             length = 1
#             for j in range(i+1, n):
#                 if arr[j] == cur + difference:
#                     length += 1
#                     cur = arr[j]
#             ret = max(ret, length)
        
#         return ret