Minimum increments or decrements required to convert a sorted array into a power sequence | Function to find the minimum number of increments or decrements required to convert array into a power sequence ; Initialize the count to f ( X ) for X = 1 ; Calculate the value of f ( X ) X ^ ( n - 1 ) <= f ( 1 ) + a [ n - 1 ] ; Calculate F ( x ) ; Check if X ^ ( n - 1 ) > f ( 1 ) + a [ n - 1 ] ; Update ans to store the minimum of ans and F ( x ) ; Return the minimum number of operations required ; Driver Code
function minOperations ( a , n ) { var ans = 0 ; for ( i = 0 ; i < n ; i ++ ) { ans += a [ i ] ; } ans -= n ; for ( x = 1 ; ; x ++ ) { var curPow = 1 , curCost = 0 ; for ( i = 0 ; i < n ; i ++ ) { curCost += Math . abs ( a [ i ] - curPow ) ; curPow *= x ; } if ( curPow / x > ans + a [ n - 1 ] ) break ; ans = Math . min ( ans , curCost ) ; } return ans ; } var arr = [ 1 , 5 , 7 ] ; var N = arr . length ; document . write ( minOperations ( arr , N ) ) ;