<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 {
public:
    int solve(int i,int p,vector<int>& arr, int d ){
        if(i==arr.size()) return 0;
        int t=0;
        if(p==-1||arr[i]-arr[p]==d){
           t=1+solve(i+1,i,arr,d);
        }
        int m=solve(i+1,p,arr,d);
        return max(m,t);
    }
    int longestSubsequence(vector<int>& arr, int d) {
        // int k=0;
        // int n=arr.size();
        // // vector<vector<int>> v(n+1,vector<int>(n+1));
        // vector<int> next(n+1);
        // vector<int> curr(n+1);
        // for(int i=n-1;i>=0;i--){
        //     for(int j=i-1;j>=-1;j--){
        //         int t=0;
        //         if(j==-1||arr[i]-arr[j]==d){
        //           t=1+next[i+1];
        //         }
        //         int m=next[j+1];
        //         curr[j+1]=max(t,m);
        //     }
        //     next=curr;
        // }
        // return curr[0];
        map<int,int> np;
        int m=0;
        for(int i=0;i<arr.size();i++){
            if(np.find(arr[i]-d)==np.end()){
                np[arr[i]]=1;
            }
            else np[arr[i]]=1+np[arr[i]-d];
            m=max(m,np[arr[i]]);
        }
          return m;
    }
};
60200