text: Minimize array elements required to be incremented or decremented to convert given array into a Fibonacci Series | Java 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 java . util . * ; class GFG { static int minMoves ( int [ ] arr ) { int N = arr . length ; if ( N <= 2 ) return 0 ; int ans = Integer . MAX_VALUE ; for ( int i = - 1 ; i <= 1 ; i ++ ) { for ( int j = - 1 ; j <= 1 ; j ++ ) { int num1 = arr [ 0 ] + i ; int num2 = arr [ 1 ] + j ; int flag = 1 ; int moves = Math . abs ( i ) + Math . abs ( j ) ; for ( int idx = 2 ; idx < N ; idx ++ ) { int num = num1 + num2 ; if ( Math . abs ( arr [ idx ] - num ) > 1 ) flag = 0 ; else moves += Math . abs ( arr [ idx ] - num ) ; num1 = num2 ; num2 = num ; } if ( flag > 0 ) ans = Math . min ( ans , moves ) ; } } if ( ans == Integer . MAX_VALUE ) return - 1 ; return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 4 , 8 , 9 , 17 , 27 } ; System . out . print ( minMoves ( arr ) ) ; } }