LeetCode Solutions

453. Minimum Moves to Equal Array Elements

Time: $O(n)$

Space: $O(1)$

			

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); });
  }
};
			

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;
  }
}
			

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