Minimum Moves to Equal Array Elements II in Python

PythonServer Side ProgrammingProgramming

Suppose we have a non-empty integer array, we have to find the minimum number of moves that are required to make all array elements equal, where a move is incrementing or decrementing a selected element by 1. So when the array is like [1, 2, 3], then the output will be 2, as 1 will be incremented to 2, and 3 will be decremented to 2.

To solve this, we will follow these steps −

  • sort the array nums
  • set counter as 0
  • for i in nums, do
    • counter := counter + absolute of (i – nums[length of nums / 2])
  • return counter

Example(Python)

Let us see the following implementation to get a better understanding −

 Live Demo

class Solution:
   def minMoves2(self, nums):
      nums.sort()
      counter = 0
      for i in nums:
         counter += abs(i-nums[len(nums)//2])
      return counter
ob1 = Solution()
print(ob1.minMoves2([2,5,3,4]))

Input

[2,5,3,4]

Output

4
raja
Published on 27-Feb-2020 10:02:53
Advertisements