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 mn = ranges::min(nums);
    return accumulate(nums.begin(), nums.end(), 0, [&](int subtotal, int num) {
      return subtotal + (num - mn);
    });
  }
};
1
2
3
4
5
6
7
class Solution {
  public int minMoves(int[] nums) {
    final int sum = Arrays.stream(nums).sum();
    final int mn = Arrays.stream(nums).min().getAsInt();
    return sum - mn * nums.length;
  }
}
1
2
3
4
class Solution:
  def minMoves(self, nums: list[int]) -> int:
    mn = min(nums)
    return sum(num - mn for num in nums)