Minimum Moves to Equal Array Elements
You're given an integer array nums. In a single move, you may pick any n - 1 of its elements (that is, all but one) and increase each of them by 1. Determine the smallest number of such moves needed to make every element in the array equal.
Input Format
Implement minMoves(nums). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
nums = [1,2,3] Output
3 Example 2
Input
nums = [1,1,1] Output
0 Constraints
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
Test Cases (2)
Case 1
Args: [[1,2,3]]
Expected: 3
Case 2
Args: [[1,1,1]]
Expected: 0
Math Insight
Incrementing n-1 elements by 1 is equivalent to decrementing 1 element by 1. Answer = sum - n * min.
function minMoves(nums) {
const min = Math.min(...nums);
return nums.reduce((sum, n) => sum + n - min, 0);
}Time: O(n) | Space: O(1)
Saved in this browser only. Private to you.