题意:
给定一个整数数组 A,返回 A 中最长等差子序列的长度。
回想一下,A 的子序列是列表 A[i_1], A[i_2], …, A[i_k] 其中 0 <= i_1 < i_2 < … < i_k <= A.length - 1。并且如果 B[i+1] - B[i]( 0 <= i < B.length - 1) 的值都相同,那么序列 B 是等差的。
思路:
dp[i][j]表示A[i]的前面公差为j的数量
则若A[X]-A[i] == j 则dp[x][j] = dp[i][j]+1
再维护一个最大序列
code:
class Solution:
def longestArithSeqLength(self, A: List[int]) -> int:
max_l = 0
diff_dict = {}
for i in range(0, len(A)):
diff_dict[i] = {}
for j in range(0, i):
diff = A[i] - A[j]
if diff not in diff_dict[j]:
diff_dict[i][diff] = 2
else:
diff_dict[i][diff] = diff_dict[j][diff] + 1
if diff_dict[i][diff] > max_l:
max_l = diff_dict[i][diff]
return max_l
来源:CSDN
作者:一个莫得感情的代码机器
链接:https://blog.csdn.net/silence255713/article/details/103469667