Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Minimize array elements required to be incremented or decremented to convert given array into a Fibonacci Series

  • Last Updated : 04 May, 2021

Given an array arr[], the task is to find the minimum number increments or decrements by 1 required to convert the array into a Fibonacci Series. If it is not possible, then print -1
Note: Each array element can be incremented or decremented only once.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {4, 8, 9, 17, 21}
Output: 3
Explanation:
The array can be converted into a Fibonacci Series in three moves:
Convert 4 to 3, arr[] = {3, 8, 9, 17, 21}
Convert 8 to 7, arr[] = {3, 7, 9, 17, 21}
Convert 9 to 10, arr[] = {3, 7, 10, 17, 21}

Input: arr[] = {3, 8, 7, 2}
Output: -1
Explanation:
The given array cannot be converted into a Fibonacci Series.



Approach: The idea to solve the problem is to use the fact that the first two elements of a Fibonacci Series are enough to calculate the common difference of the Fibonacci Series and hence the subsequent elements. So check all permutations of operations on the first two numbers and calculate the minimum moves to convert the rest of the elements into Fibonacci Series.
Follow the steps below to implement the above approach:

  • If the number of elements in the array is less than 3, then it’s already a Fibonacci series.
  • Otherwise, try all permutations of the first two elements:
    • For each permutation, calculate the number of operations for the rest of the elements of the array:
      • If it’s not possible to change the element in at most one operation, then the array cannot be converted into a Fibonacci Series.
      • Otherwise, update the required number of operations.
    • Update the answer with the number of operations.
  • Return the answer.

Below is the implementation of our approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate minimum
// number of moves to make the
// sequence a Fibonacci series
int minMoves(vector<int> arr)
{
    int N = arr.size();
 
    // If number of elements
    // is less than 3
    if (N <= 2)
        return 0;
 
    // Initialize the value
    // of the result
    int ans = INT_MAX;
 
    // Try all permutations of
    // the first two elements
    for (int i = -1; i <= 1; i++) {
        for (int j = -1; j <= 1; j++) {
 
            // Value of first element
            // after operation
            int num1 = arr[0] + i;
 
            // Value of second element
            // after operation
            int num2 = arr[1] + j;
 
            int flag = 1;
            int moves = abs(i) + abs(j);
 
            // Calculate number of moves
            // for rest of the elements
            // of the array
            for (int idx = 2; idx < N; idx++) {
 
                // Element at idx index
                int num = num1 + num2;
 
                // If it is not possible
                // to change the element
                // in atmost one move
                if (abs(arr[idx] - num) > 1)
                    flag = 0;
 
                // Otherwise
                else
                    moves += abs(arr[idx] - num);
 
                num1 = num2;
                num2 = num;
            }
 
            // Update the answer
            if (flag)
                ans = min(ans, moves);
        }
    }
 
    // Return the answer
    if (ans == INT_MAX)
        return -1;
    return ans;
}
 
// Driver Code
int main()
{
    vector<int> arr = { 4, 8, 9, 17, 27 };
    cout << minMoves(arr) << endl;
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to calculate minimum
// number of moves to make the
// sequence a Fibonacci series
static int minMoves(int []arr)
{
    int N = arr.length;
 
    // If number of elements
    // is less than 3
    if (N <= 2)
        return 0;
 
    // Initialize the value
    // of the result
    int ans = Integer.MAX_VALUE;
 
    // Try all permutations of
    // the first two elements
    for (int i = -1; i <= 1; i++)
    {
        for (int j = -1; j <= 1; j++)
        {
 
            // Value of first element
            // after operation
            int num1 = arr[0] + i;
 
            // Value of second element
            // after operation
            int num2 = arr[1] + j;
            int flag = 1;
            int moves = Math.abs(i) + Math.abs(j);
 
            // Calculate number of moves
            // for rest of the elements
            // of the array
            for (int idx = 2; idx < N; idx++)
            {
 
                // Element at idx index
                int num = num1 + num2;
 
                // If it is not possible
                // to change the element
                // in atmost one move
                if (Math.abs(arr[idx] - num) > 1)
                    flag = 0;
 
                // Otherwise
                else
                    moves += Math.abs(arr[idx] - num);
                num1 = num2;
                num2 = num;
            }
 
            // Update the answer
            if (flag > 0)
                ans = Math.min(ans, moves);
        }
    }
 
    // Return the answer
    if (ans == Integer.MAX_VALUE)
        return -1;
    return ans;
}
 
// Driver Code
public static void main(String[] args)
{
    int []arr = { 4, 8, 9, 17, 27 };
    System.out.print(minMoves(arr));
}
}
 
// This code is contributed by 29AjayKumar

Python3




# Python3 program for the above approach
import sys
 
# Function to calculate minimum
# number of moves to make the
# sequence a Fibonacci series
def minMoves(arr):
    N = len(arr)
 
    # If number of elements
    # is less than 3
    if (N <= 2):
        return 0
 
    # Initialize the value
    # of the result
    ans = sys.maxsize
 
    # Try all permutations of
    # the first two elements
    for i in range(-1, 2):
        for j in range(-1, 2):
 
            # Value of first element
            # after operation
            num1 = arr[0] + i
 
            # Value of second element
            # after operation
            num2 = arr[1] + j
            flag = 1
            moves = abs(i) + abs(j)
 
            # Calculate number of moves
            # for rest of the elements
            # of the array
            for idx in range(2, N):
 
                # Element at idx index
                num = num1 + num2
 
                # If it is not possible
                # to change the element
                # in atmost one move
                if (abs(arr[idx] - num) > 1):
                    flag = 0
 
                # Otherwise
                else:
                    moves += abs(arr[idx] - num)
                num1 = num2
                num2 = num
 
            # Update the answer
            if (flag):
                ans = min(ans, moves)
 
    # Return the answer
    if (ans == sys.maxsize):
        return -1
    return ans
 
# Driver Code
if __name__ == "__main__":
    arr = [4, 8, 9, 17, 27]
    print(minMoves(arr))
 
    # This code is contributed by chitranayal

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
// Function to calculate minimum
// number of moves to make the
// sequence a Fibonacci series
class GFG{
 
static int minMoves(List<int> arr)
{
    int N = arr.Count;
 
    // If number of elements
    // is less than 3
    if (N <= 2)
        return 0;
 
    // Initialize the value
    // of the result
    int ans = Int32.MaxValue;
 
    // Try all permutations of
    // the first two elements
    for(int i = -1; i <= 1; i++)
    {
        for(int j = -1; j <= 1; j++)
        {
             
            // Value of first element
            // after operation
            int num1 = arr[0] + i;
 
            // Value of second element
            // after operation
            int num2 = arr[1] + j;
 
            int flag = 1;
            int moves = Math.Abs(i) + Math.Abs(j);
 
            // Calculate number of moves
            // for rest of the elements
            // of the array
            for(int idx = 2; idx < N; idx++)
            {
                 
                // Element at idx index
                int num = num1 + num2;
 
                // If it is not possible
                // to change the element
                // in atmost one move
                if (Math.Abs(arr[idx] - num) > 1)
                    flag = 0;
 
                // Otherwise
                else
                    moves += Math.Abs(arr[idx] - num);
 
                num1 = num2;
                num2 = num;
            }
 
            // Update the answer
            if (flag != 0)
                ans = Math.Min(ans, moves);
        }
    }
 
    // Return the answer
    if (ans == Int32.MaxValue)
        return -1;
         
    return ans;
}
 
// Driver Code
public static void Main()
{
    List<int> arr = new List<int>(){ 4, 8, 9, 17, 27 };
     
    Console.WriteLine(minMoves(arr));
}
}
 
// This code is contributed by SURENDRA_GANGWAR

Javascript




<script>
// javascript program of the above approach
 
// Function to calculate minimum
// number of moves to make the
// sequence a Fibonacci series
function minMoves(arr)
{
    let N = arr.length;
  
    // If number of elements
    // is less than 3
    if (N <= 2)
        return 0;
  
    // Initialize the value
    // of the result
    let ans = Number.MAX_VALUE;
  
    // Try all permutations of
    // the first two elements
    for (let i = -1; i <= 1; i++)
    {
        for (let j = -1; j <= 1; j++)
        {
  
            // Value of first element
            // after operation
            let num1 = arr[0] + i;
  
            // Value of second element
            // after operation
            let num2 = arr[1] + j;
            let flag = 1;
            let moves = Math.abs(i) + Math.abs(j);
  
            // Calculate number of moves
            // for rest of the elements
            // of the array
            for (let idx = 2; idx < N; idx++)
            {
  
                // Element at idx index
                let num = num1 + num2;
  
                // If it is not possible
                // to change the element
                // in atmost one move
                if (Math.abs(arr[idx] - num) > 1)
                    flag = 0;
  
                // Otherwise
                else
                    moves += Math.abs(arr[idx] - num);
                num1 = num2;
                num2 = num;
            }
  
            // Update the answer
            if (flag > 0)
                ans = Math.min(ans, moves);
        }
    }
  
    // Return the answer
    if (ans == Number.MAX_VALUE)
        return -1;
    return ans;
}
  
    // Driver Code
     
    let arr = [ 4, 8, 9, 17, 27 ];
    document.write(minMoves(arr));
  
 // This code is contributed by chinmoy1997pal.
</script>
Output: 
3

 

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!