Skip to content

Commit 8c2bf47

Browse files
authored
Create length-of-longest-fibonacci-subsequence.cpp
1 parent 2a812c3 commit 8c2bf47

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// Time: O(n^2)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int lenLongestFibSubseq(vector<int>& A) {
7+
unordered_set<int> lookup(A.cbegin(), A.cend());
8+
int result = 0;
9+
for (int i = 0; i < A.size(); ++i) {
10+
for (int j = i + 1; j < A.size(); ++j) {
11+
int x = A[i], y = A[j], l = 2;
12+
while (lookup.count(x + y)) {
13+
y = x + y, x = y - x, ++l;
14+
}
15+
result = max(result, l);
16+
}
17+
}
18+
return result > 2 ? result : 0;
19+
}
20+
};

0 commit comments

Comments
 (0)