Skip to content

Commit 49d0860

Browse files
committed
Sync LeetCode submission Runtime - 846 ms (61.26%), Memory - 18.1 MB (74.83%)
1 parent 48bcae1 commit 49d0860

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<p>A sequence <code>x<sub>1</sub>, x<sub>2</sub>, ..., x<sub>n</sub></code> is <em>Fibonacci-like</em> if:</p>
2+
3+
<ul>
4+
<li><code>n &gt;= 3</code></li>
5+
<li><code>x<sub>i</sub> + x<sub>i+1</sub> == x<sub>i+2</sub></code> for all <code>i + 2 &lt;= n</code></li>
6+
</ul>
7+
8+
<p>Given a <b>strictly increasing</b> array <code>arr</code> of positive integers forming a sequence, return <em>the <strong>length</strong> of the longest Fibonacci-like subsequence of</em> <code>arr</code>. If one does not exist, return <code>0</code>.</p>
9+
10+
<p>A <strong>subsequence</strong> is derived from another sequence <code>arr</code> by deleting any number of elements (including none) from <code>arr</code>, without changing the order of the remaining elements. For example, <code>[3, 5, 8]</code> is a subsequence of <code>[3, 4, 5, 6, 7, 8]</code>.</p>
11+
12+
<p>&nbsp;</p>
13+
<p><strong class="example">Example 1:</strong></p>
14+
15+
<pre>
16+
<strong>Input:</strong> arr = [1,2,3,4,5,6,7,8]
17+
<strong>Output:</strong> 5
18+
<strong>Explanation:</strong> The longest subsequence that is fibonacci-like: [1,2,3,5,8].</pre>
19+
20+
<p><strong class="example">Example 2:</strong></p>
21+
22+
<pre>
23+
<strong>Input:</strong> arr = [1,3,7,11,12,14,18]
24+
<strong>Output:</strong> 3
25+
<strong>Explanation</strong>:<strong> </strong>The longest subsequence that is fibonacci-like: [1,11,12], [3,11,14] or [7,11,18].</pre>
26+
27+
<p>&nbsp;</p>
28+
<p><strong>Constraints:</strong></p>
29+
30+
<ul>
31+
<li><code>3 &lt;= arr.length &lt;= 1000</code></li>
32+
<li><code>1 &lt;= arr[i] &lt; arr[i + 1] &lt;= 10<sup>9</sup></code></li>
33+
</ul>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Approach 1: Brute Force
2+
3+
# M = largest number in arr
4+
# Time: O(n^2 log M)
5+
# Space: O(n)
6+
7+
class Solution:
8+
def lenLongestFibSubseq(self, arr: List[int]) -> int:
9+
num_set = set(arr)
10+
max_len = 0
11+
n = len(arr)
12+
13+
for start in range(n):
14+
for next in range(start + 1, n):
15+
prev = arr[next]
16+
curr = arr[start] + arr[next]
17+
curr_len = 2
18+
19+
while curr in num_set:
20+
prev, curr = curr, curr + prev
21+
curr_len += 1
22+
max_len = max(max_len, curr_len)
23+
24+
return max_len
25+

0 commit comments

Comments
 (0)