[Geeks for Geeks] Longest Arithmetic Progression

Longest Arithmetic Progression

Given an array called A[] of sorted integers having no duplicates, find the length of the Longest Arithmetic Progression (LLAP) in it.

  • Time : O(n^2)
  • Space : O(n^2)
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
class Solution{
unordered_map<int, int> table;
unordered_map<int, int> dp[1000];
int helper(int n, int d, int pos) {
if(dp[pos].count(d)) return dp[pos][d];
dp[pos][d] = 1;
if(table.count(n + d))
dp[pos][d] += helper(n + d, d, table[n + d]);
return dp[pos][d];
}
public:
int lengthOfLongestAP(int A[], int n) {
if(n == 1) return 1;
table.clear();
int res = 0;
for(int i = n - 1; i >= 0; i--) {
dp[i].clear();
table[A[i]] = i;
for(int j = i + 1; j < n; j++) {
res = max(res, helper(A[i], A[j] - A[i], i));
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/26/PS/GeeksforGeeks/longest-arithmetic-progression/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.