-
Notifications
You must be signed in to change notification settings - Fork 242
/
Copy pathLongestArithmeticSubsequence.cpp
80 lines (61 loc) · 1.98 KB
/
LongestArithmeticSubsequence.cpp
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// https://leetcode.com/problems/longest-arithmetic-subsequence/description/
class Solution {
public:
// Simple Recursive Solution
// int solve(vector<int>& nums, int i, int diff){
// if(i<=0)
// return 0;
// int ans= 0;
// for(int j=i-1; j>=0; j--){
// if(nums[i]-nums[j] == diff){
// ans= max(ans, 1 + solve(nums, j, diff));
// }
// }
// return ans;
// }
// Recursion + Memoization (Top-Down Approach)
// int solve(vector<int>& nums, int i, int diff, unordered_map<int,int> dp[]){
// if(i<=0)
// return 0;
// if(dp[i].count(diff))
// return dp[i][diff];
// int ans= 0;
// for(int j=i-1; j>=0; j--){
// if(nums[i]-nums[j] == diff){
// ans= max(ans, 1 + solve(nums, j, diff, dp));
// }
// }
// dp[i][diff]= ans;
// return dp[i][diff];
// }
int solve(vector<int>& nums){
unordered_map<int,int> dp[nums.size()+1];
int ans= 0;
for(int i= 1; i<nums.size(); i++){
for(int j=0; j<i; j++){
int diff= nums[i]-nums[j];
int count= 1;
if(dp[j].count(diff))
count= dp[j][diff];
dp[i][diff]= 1+count;
ans= max(ans, dp[i][diff]);
}
}
return ans;
}
int longestArithSeqLength(vector<int>& nums) {
if(nums.size()<2)
return nums.size();
// unordered_map<int,int> dp[nums.size()];
// int ans= 0;
// for(int i=0; i<nums.size(); i++){
// for(int j= i+1; j<nums.size(); j++){
// // Simple Recursive Solution
// // ans= max(ans, 2 + solve(nums, i, nums[j]-nums[i]));
// ans= max(ans, 2 + solve(nums, i, nums[j]-nums[i], dp));
// }
// }
// return ans;
return solve(nums);
}
};