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


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 −

Example

 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]
print(ob.solve(nums))

Input

[2, 4, 5]

Output

5

Updated on: 06-Oct-2020

407 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements