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