Skip to content

453. Minimum Moves to Equal Array Elements 👎

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
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); });
  }
};
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)