Length of longest subsequence of Fibonacci Numbers in an Array

Given an array arr containing non-negative integers, the task is to print the length of the longest subsequence of Fibonacci numbers in this array.

Examples:

Input: arr[] = { 3, 4, 11, 2, 9, 21 }
Output: 3
Here, the subsequence is {3, 2, 21} and hence the answer is 3.

Input: arr[] = { 6, 4, 10, 13, 9, 25 }
Output: 1
Here, the subsequence is {1} and hence the answer is 1.

Approach:



  • Build hash table containing all the Fibonacci numbers which will be used to test a number in O(1) time.
  • Now, we will traverse through the given array.
  • We will include all the Fibonacci numbers that we encounter during our traversal into the longest subsequence and hence increase the answer by 1 for every encounter of a Fibonacci number.
  • Once the entire initial array has been encountered, we have the length of the longest subsequence containing only Fibonacci numbers with us.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the length
// of longest subsequence of
// Fibonacci Numbers in an Array
  
#include <bits/stdc++.h>
using namespace std;
#define N 100005
  
// Function to create hash table
// to check Fibonacci numbers
void createHash(set<int>& hash,
                int maxElement)
{
    int prev = 0, curr = 1;
    hash.insert(prev);
    hash.insert(curr);
  
    while (curr <= maxElement) {
        int temp = curr + prev;
        hash.insert(temp);
        prev = curr;
        curr = temp;
    }
}
  
// Function to find the longest
// subsequence containing
// all Fibonacci numbers
int longestFibonacciSubsequence(
    int arr[], int n)
{
    set<int> hash;
    createHash(
        hash,
        *max_element(arr, arr + n));
  
    int answer = 0;
  
    for (int i = 0; i < n; i++) {
        if (hash.find(arr[i])
            != hash.end()) {
            answer++;
        }
    }
  
    return answer;
}
  
// Driver code
int main()
{
    int arr[] = { 3, 4, 11, 2, 9, 21 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call
    cout << longestFibonacciSubsequence(arr, n)
         << endl;
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the length
// of longest subsequence of
// Fibonacci Numbers in an Array
import java.util.*;
  
class GFG{
static final int N = 100005;
   
// Function to create hash table
// to check Fibonacci numbers
static void createHash(HashSet<Integer> hash,
                int maxElement)
{
    int prev = 0, curr = 1;
    hash.add(prev);
    hash.add(curr);
   
    while (curr <= maxElement) {
        int temp = curr + prev;
        hash.add(temp);
        prev = curr;
        curr = temp;
    }
}
   
// Function to find the longest
// subsequence containing
// all Fibonacci numbers
static int longestFibonacciSubsequence(
    int arr[], int n)
{
    HashSet<Integer> hash = new HashSet<Integer>();
    createHash(
        hash,Arrays.stream(arr).max().getAsInt());
   
    int answer = 0;
   
    for (int i = 0; i < n; i++) {
        if (hash.contains(arr[i])) {
            answer++;
        }
    }
   
    return answer;
}
   
// Driver code
public static void main(String[] args)
{
    int arr[] = { 3, 4, 11, 2, 9, 21 };
    int n = arr.length;
   
    // Function call
    System.out.print(longestFibonacciSubsequence(arr, n)
         +"\n");
   
}
}
  
// This code contributed by Princi Singh

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to find the length
# of longest subsequence of
# Fibonacci Numbers in an Array
  
N = 100005
  
# Function to create hash table
# to check Fibonacci numbers
def createHash(hash,maxElement):
    prev = 0
    curr = 1
    hash.add(prev)
    hash.add(curr)
  
    while (curr <= maxElement):
        temp = curr + prev
        hash.add(temp)
        prev = curr
        curr = temp
      
# Function to find the longest
# subsequence containing
# all Fibonacci numbers
def longestFibonacciSubsequence(arr, n):
    hash = set()
    createHash(hash,max(arr))
  
    answer = 0
  
    for i in range(n):
        if (arr[i] in hash):
            answer += 1
  
    return answer
  
# Driver code
if __name__ == '__main__':
    arr = [3, 4, 11, 2, 9, 21]
    n = len(arr)
  
    # Function call
    print(longestFibonacciSubsequence(arr, n))
  
# This code is contributed by Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the length
// of longest subsequence of
// Fibonacci Numbers in an Array
using System;
using System.Linq;
using System.Collections.Generic;
  
class GFG{
static readonly int N = 100005;
    
// Function to create hash table
// to check Fibonacci numbers
static void createHash(HashSet<int> hash,
                int maxElement)
{
    int prev = 0, curr = 1;
    hash.Add(prev);
    hash.Add(curr);
    
    while (curr <= maxElement) {
        int temp = curr + prev;
        hash.Add(temp);
        prev = curr;
        curr = temp;
    }
}
    
// Function to find the longest
// subsequence containing
// all Fibonacci numbers
static int longestFibonacciSubsequence(
    int []arr, int n)
{
    HashSet<int> hash = new HashSet<int>();
    createHash(hash,arr.Max());
    
    int answer = 0;
    
    for (int i = 0; i < n; i++) {
        if (hash.Contains(arr[i])) {
            answer++;
        }
    }
    
    return answer;
}
    
// Driver code
public static void Main(String[] args)
{
    int []arr = { 3, 4, 11, 2, 9, 21 };
    int n = arr.Length;
    
    // Function call
    Console.Write(longestFibonacciSubsequence(arr, n)
         +"\n");
}
}
  
// This code is contributed by sapnasingh4991

chevron_right


Output:

3

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




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.