-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathLength of Longest Fibonacci Subsequence.cpp
52 lines (39 loc) · 1.15 KB
/
Length of Longest Fibonacci Subsequence.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
// Runtime: 633 ms (Top 77.58%) | Memory: 145.9 MB (Top 23.71%)
class Solution {
public:
int help(int i,int j, unordered_map<int,int> &mp,vector<int> &nums , vector<vector<int>> &dp){
if(dp[i][j]!=-1)
return dp[i][j];
int x=nums[i]+nums[j];
if(mp.find(x)!=mp.end())
{
dp[i][j]=help(j,mp[x],mp,nums,dp);
return 1+dp[i][j];
}
return 1;
}
int solve(int idx ,int n, unordered_map<int,int> &mp,vector<int> &nums , vector<vector<int>> &dp)
{
int maxi=INT_MIN;
for(int i=idx;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
int x=nums[i]+nums[j];
if(mp.find(x)!=mp.end())
{
maxi=max(maxi,2+help(j,mp[x],mp,nums,dp));
}
}
}
return (maxi==INT_MIN?0:maxi);
}
int lenLongestFibSubseq(vector<int>& arr) {
unordered_map<int,int> mp;
int n=arr.size();
vector<vector<int>> dp(n,vector<int> (n,-1));
for(int i=0;i<arr.size();i++)
mp[arr[i]]=i;
return solve(0,n,mp,arr,dp);
}
};