Program to make all elements equal by performing given operation in Python

PythonServer Side ProgrammingProgramming

Suppose we have given a list of numbers called nums, we want to make the values equal. Now let an operation where we pick one element from the list and increment every other value. We have to find the minimum number of operations required to make element values equal.

So, if the input is like [2, 4, 5], then the output will be 5.

To solve this, we will follow these steps −

  • min_val := minimum of nums
  • s := 0
  • for each num in nums, do
    • s := s + (num - min_val)
  • return s

Let us see the following implementation to get better understanding −


 Live Demo

class Solution:
   def solve(self, nums):
      min_val = min(nums)
      s = 0
      for num in nums:
         s += num - min_val
      return s
ob = Solution()
nums = [2, 4, 5]


[2, 4, 5]


Published on 06-Oct-2020 06:16:55