Skip to content

Commit ce1dd76

Browse files
authored
Create length-of-longest-fibonacci-subsequence.py
1 parent 8c2bf47 commit ce1dd76

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Time: O(n^2)
2+
# Space: O(n)
3+
4+
# A sequence X_1, X_2, ..., X_n is fibonacci-like if:
5+
#
6+
# n >= 3
7+
# X_i + X_{i+1} = X_{i+2} for all i + 2 <= n
8+
# Given a strictly increasing array A of positive integers forming a sequence,
9+
# find the length of the longest fibonacci-like subsequence of A.
10+
# If one does not exist, return 0.
11+
#
12+
# (Recall that a subsequence is derived from another sequence A by
13+
# deleting any number of elements (including none) from A,
14+
# without changing the order of the remaining elements.
15+
# For example, [3, 5, 8] is a subsequence of [3, 4, 5, 6, 7, 8].)
16+
#
17+
# Example 1:
18+
#
19+
# Input: [1,2,3,4,5,6,7,8]
20+
# Output: 5
21+
# Explanation:
22+
# The longest subsequence that is fibonacci-like: [1,2,3,5,8].
23+
# Example 2:
24+
#
25+
# Input: [1,3,7,11,12,14,18]
26+
# Output: 3
27+
# Explanation:
28+
# The longest subsequence that is fibonacci-like:
29+
# [1,11,12], [3,11,14] or [7,11,18].
30+
#
31+
# Note:
32+
# - 3 <= A.length <= 1000
33+
# - 1 <= A[0] < A[1] < ... < A[A.length - 1] <= 10^9
34+
# - (The time limit has been reduced by 50% for submissions in Java, C, and C++.)
35+
36+
class Solution(object):
37+
def lenLongestFibSubseq(self, A):
38+
"""
39+
:type A: List[int]
40+
:rtype: int
41+
"""
42+
lookup = set(A)
43+
result = 2
44+
for i in xrange(len(A)):
45+
for j in xrange(i+1, len(A)):
46+
x, y, l = A[i], A[j], 2
47+
while x+y in lookup:
48+
x, y, l = y, x+y, l+1
49+
result = max(result, l)
50+
return result if result > 2 else 0

0 commit comments

Comments
 (0)