453. The minimum number of moves to make the array elements equal-Java

Given a non-empty integer array of length n, find the minimum number of moves that make all elements of the array equal. Each movement will increase n-1 elements by 1.

Example:

Input: [1,2,3]

Output: 3

Explanation: Only 3 moves are required (note that each move increases the value of two elements):

[1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]

Source: LeetCode
Link: https://leetcode-cn.com/problems/minimum-moves-to-equal-array-elements

Method 1: Add 1 to n-1 elements, which is equivalent to subtract 1 from 1 element.

public static int minMoves(int[] nums) {
    
    
    Arrays.sort(nums);
    int sum = 0;
    for (int i = 1; i < nums.length; i++) {
    
    
        sum += nums[i] - nums[0];
    }
    return sum;
}

Guess you like

Origin blog.csdn.net/m0_46390568/article/details/108040271