Minimize count of divisions by D to obtain at least K equal array elements | 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
def getMinimumMoves ( n , k , d , a ) : NEW_LINE INDENT MAX = 100000 NEW_LINE v = [ ] NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT v . append ( [ ] ) NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT cnt = 0 NEW_LINE v [ a [ i ] ] += [ 0 ] NEW_LINE while ( a [ i ] > 0 ) : NEW_LINE INDENT a [ i ] //= d NEW_LINE cnt += 1 NEW_LINE v [ a [ i ] ] += [ cnt ] NEW_LINE DEDENT DEDENT ans = float ( ' inf ' ) NEW_LINE for i in range ( MAX ) : NEW_LINE INDENT if ( len ( v [ i ] ) >= k ) : NEW_LINE INDENT move = 0 NEW_LINE v [ i ] . sort ( ) NEW_LINE for j in range ( k ) : NEW_LINE INDENT move += v [ i ] [ j ] NEW_LINE DEDENT ans = min ( ans , move ) NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 5 NEW_LINE K = 3 NEW_LINE D = 2 NEW_LINE A = [ 1 , 2 , 3 , 4 , 5 ] NEW_LINE print ( getMinimumMoves ( N , K , D , A ) ) NEW_LINE DEDENT