Find length of longest Fibonacci like subsequence
Last Updated :
07 Sep, 2022
Given a strictly increasing array A of positive integers where,
The task is to find the length of the longest Fibonacci-like subsequence of A. If such subsequence does not exist, return 0.
Examples:
Input: A = [1, 3, 7, 11, 12, 14, 18]
Output: 3
Explanation:
The longest subsequence that is Fibonacci-like: [1, 11, 12]. Other possible subsequences are [3, 11, 14] or [7, 11, 18].
Input: A = [1, 2, 3, 4, 5, 6, 7, 8]
Output: 5
Explanation:
The longest subsequence that is Fibonacci-like: [1, 2, 3, 5, 8].
Naive Approach: A Fibonacci-like sequence is such that it has each two adjacent terms that determine the next expected term.
For example, with 1, 1, we expect that the sequence must continue 2, 3, 5, 8, 13, … and so on.
- Use Set or Map to determine quickly whether the next term of Fibonacci sequence is present in the array A or not. Because of the exponential growth of these terms, there will be not more than log(M) searches to get next element on each iteration.
- For each starting pair A[i], A[j], we maintain the next expected value y = A[i] + A[j] and the previously seen largest value x = A[j]. If y is in the array, then we can then update these values (x, y) -> (y, x+y) otherwise we stop immediately.
Below is the implementation of above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int LongestFibSubseq( int A[], int n)
{
unordered_set< int > S(A, A + n);
int maxLen = 0, x, y;
for ( int i = 0; i < n; ++i) {
for ( int j = i + 1; j < n; ++j) {
x = A[j];
y = A[i] + A[j];
int length = 2;
while (S.find(y) != S.end()) {
int z = x + y;
x = y;
y = z;
maxLen = max(maxLen, ++length);
}
}
}
return maxLen >= 3 ? maxLen : 0;
}
int main()
{
int A[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
int n = sizeof (A) / sizeof (A[0]);
cout << LongestFibSubseq(A, n);
return 0;
}
|
Java
import java.util.*;
public class GFG {
static int LongestFibSubseq( int A[], int n) {
TreeSet<Integer> S = new TreeSet<>();
for ( int t : A) {
S.add(t);
}
int maxLen = 0 , x, y;
for ( int i = 0 ; i < n; ++i) {
for ( int j = i + 1 ; j < n; ++j) {
x = A[j];
y = A[i] + A[j];
int length = 3 ;
while (S.contains(y) && (y != S.last())) {
int z = x + y;
x = y;
y = z;
maxLen = Math.max(maxLen, ++length);
}
}
}
return maxLen >= 3 ? maxLen : 0 ;
}
public static void main(String[] args) {
int A[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 };
int n = A.length;
System.out.print(LongestFibSubseq(A, n));
}
}
|
Python3
def LongestFibSubseq(A, n):
S = set (A)
maxLen = 0
for i in range ( 0 , n):
for j in range (i + 1 , n):
x = A[j]
y = A[i] + A[j]
length = 2
while y in S:
z = x + y
x = y
y = z
length + = 1
maxLen = max (maxLen, length)
return maxLen if maxLen > = 3 else 0
if __name__ = = "__main__" :
A = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ]
n = len (A)
print (LongestFibSubseq(A, n))
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static int LongestFibSubseq( int []A, int n)
{
SortedSet< int > S = new SortedSet< int >();
foreach ( int t in A)
{
S.Add(t);
}
int maxLen = 0, x, y;
for ( int i = 0; i < n; ++i)
{
for ( int j = i + 1; j < n; ++j)
{
x = A[j];
y = A[i] + A[j];
int length = 3;
while (S.Contains(y) && y != last(S))
{
int z = x + y;
x = y;
y = z;
maxLen = Math.Max(maxLen, ++length);
}
}
}
return maxLen >= 3 ? maxLen : 0;
}
static int last(SortedSet< int > S)
{
int ans = 0;
foreach ( int a in S)
ans = a;
return ans;
}
public static void Main(String[] args)
{
int []A = {1, 2, 3, 4, 5, 6, 7, 8};
int n = A.Length;
Console.Write(LongestFibSubseq(A, n));
}
}
|
Javascript
<script>
function LongestFibSubseq(A, n)
{
var S = new Set(A);
var maxLen = 0, x, y;
for ( var i = 0; i < n; ++i) {
for ( var j = i + 1; j < n; ++j) {
x = A[j];
y = A[i] + A[j];
var length = 2;
while (S.has(y)) {
var z = x + y;
x = y;
y = z;
maxLen = Math.max(maxLen, ++length);
}
}
}
return maxLen >= 3 ? maxLen : 0;
}
var A = [1, 2, 3, 4, 5, 6, 7, 8];
var n = A.length;
document.write( LongestFibSubseq(A, n));
</script>
|
Complexity Analysis:
- Time Complexity: O(N2 * log(M)), where N is the length of array and M is max(A).
- Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach the idea is to implement Dynamic Programming. Initialize a dp table, dp[a, b] that represents the length of Fibonacci sequence ends up with (a, b). Then update the table as dp[a, b] = (dp[b – a, a] + 1 ) or 2
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int LongestFibSubseq( int A[], int n)
{
unordered_map< int , int > m;
int N = n, res = 0;
int dp[N][N];
for ( int j = 0; j < N; ++j) {
m[A[j]] = j;
for ( int i = 0; i < j; ++i) {
int k = m.find(A[j] - A[i]) == m.end()
? -1
: m[A[j] - A[i]];
dp[i][j] = (A[j] - A[i] < A[i] && k >= 0)
? dp[k][i] + 1
: 2;
res = max(res, dp[i][j]);
}
}
return res > 2 ? res : 0;
}
int main()
{
int A[] = { 1, 3, 7, 11, 12, 14, 18 };
int n = sizeof (A) / sizeof (A[0]);
cout << LongestFibSubseq(A, n);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static int LongestFibSubseq( int [] A, int n)
{
HashMap<Integer,Integer>m = new HashMap<>();
int N = n, res = 0 ;
int [][] dp = new int [N][N];
for ( int j = 0 ; j < N; ++j)
{
m.put(A[j], j);
for ( int i = 0 ; i < j; ++i)
{
int k = m.containsKey(A[j] - A[i])? m.get(A[j] - A[i]):- 1 ;
dp[i][j] = (A[j] - A[i] < A[i] && k >= 0 )
? dp[k][i] + 1
: 2 ;
res = Math.max(res, dp[i][j]);
}
}
return res > 2 ? res : 0 ;
}
public static void main(String args[]){
int [] A = { 1 , 3 , 7 , 11 , 12 , 14 , 18 };
int n = A.length;
System.out.println(LongestFibSubseq(A, n));
}
}
|
Python3
def LongestFibSubseq(A, n):
m = {}
N, res = n, 0
dp = [ [ 0 for i in range (N) ] for J in range (N) ]
for j in range (N):
m[A[j]] = j
for i in range (j):
k = - 1 if ((A[j] - A[i]) not in m) else m[A[j] - A[i]]
dp[i][j] = dp[k][i] + 1 if (A[j] - A[i] < A[i] and k > = 0 ) else 2
res = max (res, dp[i][j])
return res if res > 2 else 0
A = [ 1 , 3 , 7 , 11 , 12 , 14 , 18 ]
n = len (A)
print (LongestFibSubseq(A, n))
|
C#
using System;
using System.Collections.Generic;
class HelloWorld {
static int LongestFibSubseq( int [] A, int n)
{
var m = new Dictionary< int , int >();
int N = n;
int res = 0;
int [, ] dp = new int [N, N];
for ( int j = 0; j < N; ++j) {
m[A[j]] = j;
for ( int i = 0; i < j; ++i) {
int k = m.ContainsKey(A[j] - A[i])
? m[A[j] - A[i]]
: -1;
dp[i, j] = (A[j] - A[i] < A[i] && k >= 0)
? dp[k, i] + 1
: 2;
res = Math.Max(res, dp[i, j]);
}
}
return res > 2 ? res : 0;
}
static void Main()
{
int [] A = { 1, 3, 7, 11, 12, 14, 18 };
int n = A.Length;
Console.WriteLine(LongestFibSubseq(A, n));
}
}
|
Javascript
<script>
function LongestFibSubseq(A,n)
{
let m = new Map();
let N = n, res = 0;
let dp = new Array(N);
for (let i=0;i<N;i++){
dp[i] = new Array(N);
}
for (let j = 0; j < N; ++j) {
m.set(A[j],j);
for (let i = 0; i < j; ++i) {
let k = m.has(A[j] - A[i]) == false
? -1
: m.get(A[j] - A[i]);
dp[i][j] = (A[j] - A[i] < A[i] && k >= 0)
? dp[k][i] + 1
: 2;
res = Math.max(res, dp[i][j]);
}
}
return res > 2 ? res : 0;
}
let A = [ 1, 3, 7, 11, 12, 14, 18 ];
let n = A.length;
document.write(LongestFibSubseq(A, n));
</script>
|
Complexity Analysis:
- Time Complexity: O(N2), where N is the length of the array.
- Auxiliary Space: O(N2)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...