Minimum Moves to Equal Array Elements LeetCode solution in JavaScript

1
/**
2
* @param {number[]} nums
3
* @return {number}
4
*/
5
/*
6
thinking:
7
This problem can be reversed to think.
8
Add 1 to n-1 elements according to the intention of the question.
9
In fact, we can think of it as subtracting 1 from the remainder.
10
Add:[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
11
Subtracted:[1,2,3] => [1,2,2] => [1,1,2] => [1,1,1]
12
↑ Find the smallest element first, and find the sum of the differences between all elements and the smallest element,
13
which is the minimum moves.
14
*/
15
var minMoves = function (nums) {
16
if (nums == null || nums.length <= 1) return 0;
17
let min = nums[0];
18
let sum = 0;
19
for (i = 0; i < nums.length; i++) {
20
sum += nums[i];
21
min = Math.min(min, nums[i]);
22
}
23
return sum - min * nums.length;
24
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0