1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// @Title: 最长定差子序列 (Longest Arithmetic Subsequence of Given Difference)
// @Author: 15816537946@163.com
// @Date: 2021-11-05 18:39:39
// @Runtime: 100 ms
// @Memory: 9.3 MB
func longestSubsequence(arr []int, difference int) int {
	// dp to resolve this problem
	dp := make(map[int]int)
	var res int

	for _, v := range arr {
		if k, ok := dp[v-difference]; ok {
			dp[v] = k + 1
		} else {
			dp[v] = 1
		}
		res = max(res, dp[v])
	}
	return res
}

func max(a, b int) int {
	if a > b {
		return a
	}
	return b
}