Given a strictly increasing array arr
of positive integers forming a sequence, write a function lenLongestFibSubseq
that returns the length of the longest Fibonacci-like subsequence of arr
.
A sequence X1, X2, ..., Xk
is Fibonacci-like if:
k >= 3
Xi + Xi+1 = Xi+2
for all i + 2 <= k
.If there is no such sequence, return 0.
Input:
arr = [1,2,3,4,5,6,7,8]
Output:
5
Explanation:
The longest subsequence that is Fibonacci-like: [1, 2, 3, 5, 8]
k
is 3.We need to find the longest subsequence within the array that follows the Fibonacci property. To solve this, we can use a dynamic programming approach:
dp
where dp[(i, j)]
holds the length of the longest Fibonacci-like subsequence ending with elements at indices i
and j
.(i, j)
(where i < j
), compute the previous Fibonacci element as arr[j] - arr[i]
and check if it exists in the set and also comes before index i
.dp[(i, j)]
.dp
.def lenLongestFibSubseq(arr):
arr_set = set(arr)
n = len(arr)
dp = {}
max_len = 0
for i in range(n):
for j in range(i+1, n):
a, b = arr[i], arr[j]
count = 2
while a + b in arr_set:
a, b = b, a + b
count += 1
if count >= 3:
max_len = max(max_len, count)
return max_len if max_len >= 3 else 0
O(n^2)
, and each internal while loop may run approximately in O(n) at worst as we traverse through the array elements once. This leads us to an overall complexity of O(n^2 * n) = O(n^3) in the worst case.dp
and set arr_set
, which both have space complexities of O(n). Thus, the overall space complexity is O(n).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?