For each pair of indices, we can extend an arithmetic subsequence by checking the difference and updating the length for that difference. Using a hash map for each index allows us to efficiently track all possible differences.
classSolution {
public:int longestArithSeqLength(vector<int>& nums) {
int n = nums.size(), ans =0;
vector<unordered_map<int, int>> dp(n);
for (int i =0; i < n; ++i) {
for (int j =0; j < i; ++j) {
int d = nums[i] - nums[j];
dp[i][d] = max(dp[i][d], dp[j].count(d) ? dp[j][d] +1:2);
ans = max(ans, dp[i][d]);
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
funclongestArithSeqLength(nums []int) int {
n, ans:= len(nums), 0dp:= make([]map[int]int, n)
fori:=rangedp { dp[i] = map[int]int{} }
fori:=0; i < n; i++ {
forj:=0; j < i; j++ {
d:=nums[i] -nums[j]
v:=2ifdp[j][d] > 0 { v = dp[j][d] +1 }
ifv > dp[i][d] { dp[i][d] = v }
ifv > ans { ans = v }
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintlongestArithSeqLength(int[] nums) {
int n = nums.length, ans = 0;
Map<Integer, Integer>[] dp =new HashMap[n];
for (int i = 0; i < n; ++i) dp[i]=new HashMap<>();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
int d = nums[i]- nums[j];
int v = dp[j].getOrDefault(d, 1) + 1;
dp[i].put(d, Math.max(dp[i].getOrDefault(d, 0), v));
ans = Math.max(ans, dp[i].get(d));
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funlongestArithSeqLength(nums: IntArray): Int {
val n = nums.size
var ans = 0val dp = Array(n) { mutableMapOf<Int, Int>() }
for (i in0 until n) {
for (j in0 until i) {
val d = nums[i] - nums[j]
val v = dp[j].getOrDefault(d, 1) + 1 dp[i][d] = maxOf(dp[i].getOrDefault(d, 0), v)
ans = maxOf(ans, dp[i][d]!!)
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
deflongestArithSeqLength(self, nums: list[int]) -> int:
n, ans = len(nums), 0 dp = [{} for _ in range(n)]
for i in range(n):
for j in range(i):
d = nums[i] - nums[j]
v = dp[j].get(d, 1) +1 dp[i][d] = max(dp[i].get(d, 0), v)
ans = max(ans, dp[i][d])
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
impl Solution {
pubfnlongest_arith_seq_length(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut ans =0;
letmut dp =vec![std::collections::HashMap::new(); n];
for i in0..n {
for j in0..i {
let d = nums[i] - nums[j];
let v =*dp[j].get(&d).unwrap_or(&1) +1;
let entry = dp[i].entry(d).or_insert(0);
*entry = (*entry).max(v);
ans = ans.max(*entry);
}
}
ans
}
}