Skip to content

Commit 46b7c98

Browse files
committed
Add solution #873
1 parent d6915b6 commit 46b7c98

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -448,6 +448,7 @@
448448
867|[Transpose Matrix](./0867-transpose-matrix.js)|Easy|
449449
868|[Binary Gap](./0868-binary-gap.js)|Easy|
450450
872|[Leaf-Similar Trees](./0872-leaf-similar-trees.js)|Easy|
451+
873|[Length of Longest Fibonacci Subsequence](./0873-length-of-longest-fibonacci-subsequence.js)|Medium|
451452
875|[Koko Eating Bananas](./0875-koko-eating-bananas.js)|Medium|
452453
876|[Middle of the Linked List](./0876-middle-of-the-linked-list.js)|Easy|
453454
884|[Uncommon Words from Two Sentences](./0884-uncommon-words-from-two-sentences.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 873. Length of Longest Fibonacci Subsequence
3+
* https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/
4+
* Difficulty: Medium
5+
*
6+
* A sequence x1, x2, ..., xn is Fibonacci-like if:
7+
* - n >= 3
8+
* - xi + xi+1 == xi+2 for all i + 2 <= n
9+
*
10+
* Given a strictly increasing array arr of positive integers forming a sequence, return the length
11+
* of the longest Fibonacci-like subsequence of arr. If one does not exist, return 0.
12+
*
13+
* A subsequence is derived from another sequence arr by deleting any number of elements (including
14+
* none) from arr, without changing the order of the remaining elements. For example, [3, 5, 8] is
15+
* a subsequence of [3, 4, 5, 6, 7, 8].
16+
*/
17+
18+
/**
19+
* @param {number[]} arr
20+
* @return {number}
21+
*/
22+
var lenLongestFibSubseq = function(arr) {
23+
const set = new Set(arr);
24+
let max = 0;
25+
26+
for (let i = 0; i < arr.length; i++) {
27+
for (let j = i + 1; j < arr.length; j++) {
28+
let [x, y, count] = [arr[i], arr[j], 2];
29+
30+
while (set.has(x + y)) {
31+
const next = x + y;
32+
x = y;
33+
y = next;
34+
count++;
35+
}
36+
37+
max = Math.max(max, count);
38+
}
39+
}
40+
41+
return max >= 3 ? max : 0;
42+
};

0 commit comments

Comments
 (0)