Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit26b4e2c

Browse files
author
zongyanqi
committed
add Easy_453_Minimum_Moves_to_Equal_Array_Elements
1 parentbbcc2d7 commit26b4e2c

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
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+
varminMoves=function(nums){
34+
35+
varmin=nums[0];
36+
for(vari=1;i<nums.length;i++){
37+
min=Math.min(min,nums[i]);
38+
}
39+
40+
varret=0;
41+
for(i=0;i<nums.length;i++){
42+
ret+=nums[i]-min;
43+
}
44+
returnret;
45+
46+
};
47+
48+
console.log(minMoves([1,999,1000]));

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp