Open In App

Find the longest Fibonacci-like subarray of the given array

Last Updated : 13 May, 2021
Comments
Improve
Suggest changes
33 Likes
Like
Report

Given an array of N elements, the task is to find the longest subarray which is Fibonacci-like. 
A Fibonacci-like sub-array is defined as an array in which: 
 

A[i]=A[i-1]+A[i-2] where i>2

and, A[1] and A[2] can be anything.


Examples: 
 

Input : N = 5, arr[] = {2, 4, 6, 10, 2}
Output : 4
The sub-array 2, 4, 6, 10 is Fibonacci like.

Input : N = 3, arr[] = {0, 0, 0}
Output : 3
The entire array is Fibonacci-like.


 


Approach:
The idea is to observe that any array of length of less than or equal to 2 is Fibonacci-like. Now, for arrays of length greater than 2:
 

  1. Maintain a variable len initialized to 2 and a variable mx to store the maximum length so far.
  2. Start traversing the array from 3rd index.
  3. If the fibonacci like array can be extended for this index, i.e. if a[i] = a[i-1] + a[i-2] 
    • Then increment the value of variable len by 1.
    • Otherwise reinitialize the variable len to 2.
    • Store the maximum of mx and len in the variable mx for current iteration.


Below is the implementation of the above approach: 
 

C++
// C++ program to find length of longest
// Fibonacci-like subarray

#include <bits/stdc++.h>
using namespace std;

// Function to find the length of the 
// longest Fibonacci-like subarray
int longestFibonacciSubarray(int n, int a[])
{
    // Any 2 terms are Fibonacci-like
    if (n <= 2)
        return n;
    
    int len = 2;
    
    int mx = INT_MIN;
    
    for (int i = 2; i < n; i++) {
        
        // If previous subarray can be extended
        if (a[i] == a[i - 1] + a[i - 2])
            len++;
            
        // Any 2 terms are Fibonacci-like
        else
            len = 2;
            
        // Find the maximum length
        mx = max(mx, len);
    }
    
    return mx;
}

// Driver Code
int main()
{
    int n = 5;
    int a[] = {2, 4, 6, 10, 2};
    
    cout << longestFibonacciSubarray(n, a);
    
    return 0;
}
Java Python3 C# PHP JavaScript

Output: 
4

 

Time Complexity: O(N) 
Auxiliary Space: O(1)
 


Article Tags :
Practice Tags :

Similar Reads