A sequence x1,x2,…,xn is Fibonacci-like if n≥3 and xi+xi+1=xi+2 for every i with i+2≤n.
Given a strictly increasing array of positive integers arr, return the length of the longest Fibonacci-like subsequence of arr. If no such subsequence exists, return 0.
A subsequence is obtained from arr by deleting any number of elements (possibly none) without changing the order of the remaining elements.
Function Signature
def longest_fibonacci_subsequence_length(arr: list[int]) -> int:
Rules
-
The subsequence keeps the original order of
arr
. Its elements do not have to be adjacent in
arr
.
-
A chain needs at least three elements to count. Two elements on their own are never a valid answer, so the result is either
0
or at least
3
.
Constraints
-
3 <= len(arr) <= 1000
-
1 <= arr[i] < arr[i + 1] <= 10^9
Examples
Input: arr = [1, 2, 3, 4, 5, 6, 7, 8]
Output: 5
The subsequence [1, 2, 3, 5, 8] is Fibonacci-like (1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8). A six-element chain of positive increasing values would need a sixth value of at least 13, which is larger than every element here.
Input: arr = [1, 3, 7, 11, 12, 14, 18]
Output: 3
The only valid triples are [1, 11, 12], [3, 11, 14] and [7, 11, 18]. None of them extends, because 23, 25 and 29 are not in the array.
Input: arr = [1, 3, 5]
Output: 0
The only possible triple is the whole array, and 1 + 3 = 4 is not 5, so no Fibonacci-like subsequence exists.