Minimum Moves to Equal Array Elements II LeetCode solution in JavaScript

1
var minMoves2 = function (nums) {
2
// Sort the array low to high
3
nums.sort(function (a, b) {
4
return a - b;
5
});
6
let i = 0;
7
let j = nums.length - 1;
8
let res = 0;
9
/**
10
* Sum up the difference between the next highest and lowest numbers. Regardless of what number we wish to move towards, the number of moves is the same.
11
*/
12
while (i < j) {
13
res += nums[j] - nums[i];
14
i++;
15
j--;
16
}
17
return res;
18
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0