Skip to content

Commit b9b9e0d

Browse files
committed
Add C++ solution of problem #873
1 parent 9d1c1e4 commit b9b9e0d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

873/solution.cpp

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Hash table record index,
2+
// then find whether the target exists in hash table.
3+
4+
class Solution {
5+
public:
6+
int lenLongestFibSubseq(vector<int>& A) {
7+
int n = A.size();
8+
unordered_map<int, int> m; // {num, idx}
9+
for(int i = 0; i < n; i++)
10+
m[A[i]] = i;
11+
int mx = A.back();
12+
int ans = 0;
13+
for(int i = 0; i < n - 2; i++) {
14+
for(int j = i + 1; j < n - 1; j++) {
15+
int f1 = A[i];
16+
int f2 = A[j];
17+
int tmp = f1 + f2;
18+
if(!m.count(tmp))
19+
continue;
20+
21+
int cnt = 3;
22+
while(tmp <= mx) {
23+
f1 = f2;
24+
f2 = tmp;
25+
tmp = f1 + f2;
26+
if(!m.count(tmp))
27+
break;
28+
cnt++;
29+
}
30+
ans = max(ans, cnt);
31+
}
32+
}
33+
return ans;
34+
}
35+
};

0 commit comments

Comments
 (0)