Find length of longest Fibonacci like subsequence

Given a strictly increasing array A of positive integers where, 1 \leq A[i] \leq 10^{18}. 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].



Approach:
A Fibonacci-like sequence is such that it has each two adjacent terms that determines the next expected term. For example, with 1, 1, we expect that the sequence must continue 2, 3, 5, 8, 13, … and so on.

We will 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP implementation of above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to return the max Length of
// Fibonacci subsequence
int LongestFibSubseq(int A[], int n)
{
    // Store all array elements in a hash
    // table
    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;
  
            // check until next fib element is found
            while (S.find(y) != S.end()) {
  
                // next element of fib subseq
                int z = x + y;
                x = y;
                y = z;
                maxLen = max(maxLen, ++length);
            }
        }
    }
  
    return maxLen >= 3 ? maxLen : 0;
}
  
// Driver program
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;
}
  
// This code is written by Sanjit_Prasad

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of above approach 
import java.util.*;
public class GFG {
  
// Function to return the max Length of 
// Fibonacci subsequence 
    static int LongestFibSubseq(int A[], int n) {
        // Store all array elements in a hash 
        // table 
        TreeSet<Integer> S = new TreeSet<>();
        for (int t : A) {
            // Add each element into the set 
            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;
  
                // check until next fib element is found 
                while (S.contains(y) && (y != S.last())) {
  
                    // next element of fib subseq 
                    int z = x + y;
                    x = y;
                    y = z;
                    maxLen = Math.max(maxLen, ++length);
                }
            }
        }
        return maxLen >= 3 ? maxLen : 0;
    }
  
// Driver program 
    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));
    }
}
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the 
# above approach 
  
# Function to return the max Length 
# of Fibonacci subsequence 
def LongestFibSubseq(A, n): 
  
    # Store all array elements in 
    # a hash table 
    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
  
            # check until next fib 
            # element is found 
            while y in S: 
  
                # next element of fib subseq 
                z = x +
                x =
                y = z
                length += 1
                maxLen = max(maxLen, length) 
              
    return maxLen if maxLen >= 3 else 0
  
# Driver Code
if __name__ == "__main__":
  
    A = [1, 2, 3, 4, 5, 6, 7, 8
    n = len(A) 
    print(LongestFibSubseq(A, n)) 
      
# This code is contributed 
# by Rituraj Jain

chevron_right


Output:

5

Time Complexity: O(N2*log(M)), where N is the length of array and M is max(A).



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : rituraj_jain, 29AjayKumar