Minimum number of operations to convert a given sequence into a Geometric Progression | Set 2 | Java program for the above approach ; Function to find minimum cost ; Sort the array ; Maximum possible common ratios ; Iterate over all possible common ratios ; Calculate operations required for the current common ratio ; Calculate minimum cost ; Driver Code ; Given N ; Given arr [ ] ; Function Calling
import java . util . * ; class GFG { static void minCost ( int arr [ ] , int n ) { if ( n == 1 ) { System . out . print ( 0 + "NEW_LINE"); return ; } Arrays . sort ( arr ) ; float raised = 1 / ( float ) ( n - 1 ) ; float temp = ( float ) Math . pow ( arr [ n - 1 ] , raised ) ; int r = ( int ) ( temp ) + 1 ; int i , j , min_cost = Integer . MAX_VALUE ; int common_ratio = 1 ; for ( j = 1 ; j <= r ; j ++ ) { int curr_cost = 0 , prod = 1 ; for ( i = 0 ; i < n ; i ++ ) { curr_cost += Math . abs ( arr [ i ] - prod ) ; prod *= j ; if ( curr_cost >= min_cost ) break ; } if ( i == n ) { min_cost = Math . min ( min_cost , curr_cost ) ; common_ratio = j ; } } System . out . print ( min_cost + " ▁ " ) ; System . out . print ( common_ratio + " ▁ " ) ; } public static void main ( String [ ] args ) { int N = 6 ; int arr [ ] = { 1 , 11 , 4 , 27 , 15 , 33 } ; minCost ( arr , N ) ; } }