[InterviewBit] Longest Arithmetic Progression

Longest Arithmetic Progression

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
int Solution::solve(const vector<int> &a) {
unordered_map<int, int> mp;
int n = a.size();
if(n <=2) return n;
int dp[1010][1010];
int res = 2;
for(int i = 0; i < n; i++) {
for(int j = i + 1; j < n; j++) {
dp[i][j] = 2;
int who = 2 * a[i] - a[j];
if(mp.count(who)) dp[i][j] = max(dp[i][j], 1 + dp[mp[who]][i]);
res = max(res, dp[i][j]);
}
mp[a[i]] = i;
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/17/PS/interviewbit/longest-arithmetic-progression/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.