Minimum increments or decrements required to convert a sorted array into a power sequence | C ++ program for the above approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minOperations ( int a [ ] , int n ) { int ans = accumulate ( a , a + n , 0 ) - n ; for ( int x = 1 ; ; x ++ ) { int curPow = 1 , curCost = 0 ; for ( int i = 0 ; i < n ; i ++ ) { curCost += abs ( a [ i ] - curPow ) ; curPow *= x ; } if ( curPow / x > ans + a [ n - 1 ] ) break ; ans = min ( ans , curCost ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 5 , 7 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minOperations ( arr , N ) ; return 0 ; }