Created
August 4, 2021 15:57
-
-
Save vitalii-komenda/5a7e99c2b93cdc7d6ba6e98301d5c39b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getMinimumMoves = (k, d, a) => | |
{ | |
let MAX = 100000; | |
let n = a.length | |
// Stores the number of moves | |
// required to obtain respective | |
// values from the given array | |
let v = Array(MAX).fill(0) | |
for(let i = 0; i < v.length; i++) | |
v[i] = [] | |
// Traverse the array | |
for(let i = 0; i < n; i++) | |
{ | |
let cnt = 0; | |
// Insert 0 into V[a[i]] as | |
// it is the initial state | |
v[a[i]].push(0); | |
while (a[i] > 0) | |
{ | |
a[i] = Math.floor(a[i] / d); | |
cnt++; | |
// Insert the moves required | |
// to obtain current a[i] | |
v[a[i]].push(cnt); | |
} | |
} | |
let ans = Number.MAX_SAFE_INTEGER | |
// Traverse v[] to obtain | |
// minimum count of moves | |
for(let i = 0; i < MAX; i++) | |
{ | |
// Check if there are at least | |
// K equal elements for v[i] | |
if (v[i].length >= k) | |
{ | |
let move = 0; | |
v[i].sort((a,b)=>a-b) | |
// Add the sum of minimum K moves | |
for(let j = 0; j < k; j++) | |
{ | |
move += v[i][j]; | |
} | |
// Update answer | |
ans = Math.min(ans, move); | |
} | |
} | |
// Return the final answer | |
return ans; | |
} | |
arr = [64, 30, 25, 33]; | |
getMinimumMoves(2, 2, arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment