Related Articles

Related Articles

Minimize array elements required to be incremented or decremented to convert given array into a Fibonacci Series
  • Last Updated : 19 Jan, 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:

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 sulve 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.
Fullow 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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 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

chevron_right


 
 

Output: 

3

 

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

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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :