Minimum steps required to rearrange given array to a power sequence of 2 | C ++ program to implement the above approach ; Function to calculate the minimum steps required to convert given array into a power sequence of 2 ; Sort the array in ascending order ; Calculate the absolute difference between arr [ i ] and 2 ^ i for each index ; Return the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int minsteps ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { ans += abs ( arr [ i ] - pow ( 2 , i ) ) ; } return ans ; } int main ( ) { int arr [ ] = { 1 , 8 , 2 , 10 , 6 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << minsteps ( arr , n ) << endl ; return 0 ; }