Leetcode

Minimum Moves to Equal Array Elements

  • Time:O(n)
  • Space:O(1)

C++

class Solution {
 public:
  int minMoves(vector<int>& nums) {
    const int min = *min_element(begin(nums), end(nums));
    return accumulate(begin(nums), end(nums), 0,
                      [&](int a, int b) { return a + (b - min); });
  }
};

JAVA

class Solution {
  public int minMoves(int[] nums) {
    final int sum = Arrays.stream(nums).sum();
    final int min = Arrays.stream(nums).min().getAsInt();
    return sum - min * nums.length;
  }
}

Python

class Solution:
  def minMoves(self, nums: List[int]) -> int:
    mini = min(nums)
    return sum(num - mini for num in nums)