Minimize count of divisions by D to obtain at least K equal array elements | Java program to implement the above approach ; Function to return minimum number of moves required ; Stores the number of moves required to obtain respective values from the given array ; Traverse the array ; Insert 0 into V [ a [ i ] ] as it is the initial state ; Insert the moves required to obtain current a [ i ] ; Traverse v [ ] to obtain minimum count of moves ; Check if there are at least K equal elements for v [ i ] ; Add the sum of minimum K moves ; Update answer ; Return the final answer ; Driver Code
import java . util . * ; class GFG { @ SuppressWarnings ( " unchecked " ) static int getMinimumMoves ( int n , int k , int d , int [ ] a ) { int MAX = 100000 ; Vector < Integer > [ ] v = new Vector [ MAX ] ; for ( int i = 0 ; i < v . length ; i ++ ) v [ i ] = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; v [ a [ i ] ] . add ( 0 ) ; while ( a [ i ] > 0 ) { a [ i ] /= d ; cnt ++ ; v [ a [ i ] ] . add ( cnt ) ; } } int ans = Integer . MAX_VALUE ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( v [ i ] . size ( ) >= k ) { int move = 0 ; Collections . sort ( v [ i ] ) ; for ( int j = 0 ; j < k ; j ++ ) { move += v [ i ] . get ( j ) ; } ans = Math . min ( ans , move ) ; } } return ans ; } public static void main ( String [ ] args ) { int N = 5 , K = 3 , D = 2 ; int [ ] A = { 1 , 2 , 3 , 4 , 5 } ; System . out . print ( getMinimumMoves ( N , K , D , A ) ) ; } }