-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path1027.longest-arithmetic-sequence.cpp
More file actions
60 lines (53 loc) · 1.35 KB
/
1027.longest-arithmetic-sequence.cpp
File metadata and controls
60 lines (53 loc) · 1.35 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include "bits/stdc++.h"
using namespace std;
#include "Tree.h"
#define deb(x) cout<<x<<endl;
const int inf = 1e9;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef pair<int,int> pii;
#include "LinkedList.h"
void print(vi &out){
for(auto x: out) cout<<x<<" ";
cout<<endl;
}
class Solution0 {
public:
int longestArithSeqLength(vector<int>& nums) {
int n = nums.size();
int len =2;
map<int , map<int,int>> dp;
for(int i=0;i<n;i++){
for(int j=i+1;j<=n;j++){
int diff= nums[j]-nums[i];
dp[diff][j] = dp[diff].count(i) ? dp[diff][i]+1 : 2;
len= max(len,dp[diff][j]);
}
}
return len;
}
}; // time limit exceeded
class Solution {
public:
int longestArithSeqLength(vector<int>& nums) {
int n = nums.size();
int len =2;
vector<vector<int>> dp(n,vector<int>(2000,0));
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
int diff= nums[j]-nums[i]+1000;
dp[j][diff] = max(2,dp[i][diff]+1);
len = max(len, dp[j][diff]);
}
}
return len;
}
};
int main(){
Solution sol;
vector<int> nums= {3,6,9,12};
int ans = sol.longestArithSeqLength(nums);
cout<<ans;
}