Skip to content

Instantly share code, notes, and snippets.

@willy-r
Created September 17, 2020 18:17
Show Gist options
  • Save willy-r/776eedb3c7cda18d9d291510fb251b08 to your computer and use it in GitHub Desktop.
Save willy-r/776eedb3c7cda18d9d291510fb251b08 to your computer and use it in GitHub Desktop.
Given an array of increasing integers, find the length of the longest fibonacci-like subsequence of the array. If one does not exist, return 0. A sequence is “fibonacci-like” if X_i + X_{i+1} = X_{i+2}.
def fibonacci_like(arr: list):
"""Returns the length of the longest fibonacci-like subsequence of the
arr.
If one does not exist, returns 0.
"""
seen_arr = set(arr)
max_length = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
current, expected = arr[j], arr[i] + arr[j]
curr_length = 2
while expected in seen_arr:
current, expected = expected, current + expected
curr_length += 1
max_length = max(curr_length, max_length)
return max_length if max_length >= 3 else 0
if __name__ == '__main__':
CASES = (
([1, 3, 7, 11, 12, 14, 18], 3),
([1, 2, 3, 4, 5, 6, 7, 8], 5),
([1, 3, 5], 0),
)
for arr, expected in CASES:
result = fibonacci_like(arr)
assert result == expected, f'{result} != {expected}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment