Skip to content

453. Minimum Moves to Equal Array Elements

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  int minMoves(vector<int>& nums) {
    const int min = ranges::min(nums);
    return accumulate(nums.begin(), nums.end(), 0, [&](int subtotal, int num) {
      return subtotal + (num - min);
    });
  }
};
1
2
3
4
5
6
7
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;
  }
}
1
2
3
4
class Solution:
  def minMoves(self, nums: List[int]) -> int:
    mini = min(nums)
    return sum(num - mini for num in nums)