---
# System prepended metadata

title: 1218. Longest Arithmetic Subsequence of Given Difference
tags: [Leetcode, FaceBook, Arithmetic Sequence, Medium]

---

# 1218. Longest Arithmetic Subsequence of Given Difference
###### tags: `Leetcode` `Medium` `FaceBook` `Arithmetic Sequence`
## 思路
复习的时候可以和[1027. Longest Arithmetic Subsequence](https://hackmd.io/m0fvO_EdT7KfRZFWV-cdUg)一起看，一样的思路～
有点像[0001. Two Sum](https://hackmd.io/NjuumDsVS0-fPhog5Y4b3g)，拿到某个数之后，都是要找前面有没有出现过另一个数(two sum里面是找t-arr[i],这题是要找arr[i]-difference)
## Code
```java=
class Solution {
    public int longestSubsequence(int[] arr, int difference) {
        Map<Integer, Integer> map = new HashMap<>();
        int len = 0;
        for(int i = 0;i < arr.length;i++){
            map.put(arr[i], map.getOrDefault(arr[i]-difference, 0)+1);
            len = Math.max(len, map.get(arr[i]));
        }
        return len;
    }
}
```