1
+ """
2
+ Problem Link: https://leetcode.com/problems/longest-arithmetic-sequence/
3
+
4
+ Given an array A of integers, return the length of the longest arithmetic subsequence in A.
5
+ Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with
6
+ 0 <= i_1 < i_2 < ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i]
7
+ are all the same value (for 0 <= i < B.length - 1).
8
+
9
+ Example 1:
10
+ Input: [3,6,9,12]
11
+ Output: 4
12
+ Explanation:
13
+ The whole array is an arithmetic sequence with steps of length = 3.
14
+
15
+ Example 2:
16
+ Input: [9,4,7,2,10]
17
+ Output: 3
18
+ Explanation:
19
+ The longest arithmetic subsequence is [4,7,10].
20
+
21
+ Example 3:
22
+ Input: [20,1,15,3,10,5,8]
23
+ Output: 4
24
+ Explanation:
25
+ The longest arithmetic subsequence is [20,15,10,5].
26
+
27
+ Note:
28
+ 2 <= A.length <= 2000
29
+ 0 <= A[i] <= 10000
30
+ """
31
+ # Time Complexity: O(n^2)
32
+ # Space Complexity: O(n^2)
33
+ import collections
34
+ class Solution :
35
+ def longestArithSeqLength (self , A : List [int ]) -> int :
36
+ dp = collections .defaultdict (dict )
37
+ maxLength = 1
38
+ for i in range (1 ,len (A )):
39
+ for j in range (i ):
40
+ diff = A [i ] - A [j ]
41
+ dp [i ][diff ] = 1 + dp [j ].get (diff , 1 )
42
+ maxLength = max (maxLength , dp [i ][diff ])
43
+ return maxLength
44
+
45
+ class Solution1 :
46
+ def longestArithSeqLength (self , A : List [int ]) -> int :
47
+ dp = {}
48
+ for i in range (len (A )):
49
+ for j in range (i + 1 , len (A )):
50
+ diff = A [j ] - A [i ]
51
+ dp [j , diff ] = dp .get ((i , diff ), 1 ) + 1
52
+ return max (dp .values ())
0 commit comments