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
def minOperations ( a , n ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT ans += a [ i ] NEW_LINE DEDENT ans -= n NEW_LINE x = 1 NEW_LINE while ( 1 ) : NEW_LINE INDENT curPow = 1 NEW_LINE curCost = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT curCost += abs ( a [ i ] - curPow ) NEW_LINE curPow *= x NEW_LINE DEDENT if ( curPow / x > ans + a [ n - 1 ] ) : NEW_LINE INDENT break NEW_LINE DEDENT ans = min ( ans , curCost ) NEW_LINE x += 1 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 1 , 5 , 7 ] NEW_LINE N = len ( arr ) NEW_LINE print ( minOperations ( arr , N ) ) NEW_LINE DEDENT