Minimize count of divisions by D to obtain at least K equal array elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int getMinimumMoves ( int n , int k , int d , vector < int > a ) { int MAX = 100000 ; vector < int > v [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { int cnt = 0 ; v [ a [ i ] ] . push_back ( 0 ) ; while ( a [ i ] > 0 ) { a [ i ] /= d ; cnt ++ ; v [ a [ i ] ] . push_back ( cnt ) ; } } int ans = INT_MAX ; for ( int i = 0 ; i < MAX ; i ++ ) { if ( v [ i ] . size ( ) >= k ) { int move = 0 ; sort ( v [ i ] . begin ( ) , v [ i ] . end ( ) ) ; for ( int j = 0 ; j < k ; j ++ ) { move += v [ i ] [ j ] ; } ans = min ( ans , move ) ; } } return ans ; } int main ( ) { int N = 5 , K = 3 , D = 2 ; vector < int > A = { 1 , 2 , 3 , 4 , 5 } ; cout << getMinimumMoves ( N , K , D , A ) ; return 0 ; }