Skip to content

Commit 0d44d42

Browse files
authored
Create 873. Length of Longest Fibonacci Subsequence (#726)
2 parents 358539b + 606284a commit 0d44d42

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
int lenLongestFibSubseq(vector<int>& arr) {
4+
int n = arr.size();
5+
unordered_map<int,int>mp; // element->index
6+
for(int i=0; i<n; i++){
7+
mp[arr[i]] = i;
8+
}
9+
vector<vector<int>>dp(n,vector<int>(n,2));
10+
int maxLen = 0;
11+
12+
for(int i=0; i<n-1;i++){
13+
for(int j=i+1; j<n;j++){
14+
int next = arr[i] + arr[j];
15+
if(mp.find(next) != mp.end()){
16+
int k = mp[next];
17+
if(k>j){
18+
dp[j][k] = 1 + dp[i][j];
19+
maxLen = max(maxLen,dp[j][k]);
20+
}
21+
}
22+
}
23+
}
24+
return maxLen > 2 ? maxLen : 0;
25+
}
26+
};

0 commit comments

Comments
 (0)