Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 26b4e2c

Browse files
author
zongyanqi
committed
add Easy_453_Minimum_Moves_to_Equal_Array_Elements
1 parent bbcc2d7 commit 26b4e2c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Given a non-empty integer array of size n, find the minimum number of moves required to make all array elements equal, where a move is incrementing n - 1 elements by 1.
3+
4+
Example:
5+
6+
Input:
7+
[1,2,3]
8+
9+
Output:
10+
3
11+
12+
Explanation:
13+
Only three moves are needed (remember each move increments two elements):
14+
15+
[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
16+
17+
*/
18+
19+
/**
20+
*
21+
* reverse thinking!
22+
*
23+
* Adding 1 to n - 1 elements is the same as subtracting 1 from one element
24+
*
25+
* goal of making the elements in the array equal.
26+
* So, best way to do this is make all the elements in the array equal to the min element.
27+
*/
28+
29+
/**
30+
* @param {number[]} nums
31+
* @return {number}
32+
*/
33+
var minMoves = function (nums) {
34+
35+
var min = nums[0];
36+
for (var i = 1; i < nums.length; i++) {
37+
min = Math.min(min, nums[i]);
38+
}
39+
40+
var ret = 0;
41+
for (i = 0; i < nums.length; i++) {
42+
ret += nums[i] - min;
43+
}
44+
return ret;
45+
46+
};
47+
48+
console.log(minMoves([1, 999, 1000]));

0 commit comments

Comments
 (0)