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

Suppose we have a list of numbers and we want to make all values equal. We can perform an operation where we pick one element from the list and increment every other element by 1. We need to find the minimum number of operations required to make all element values equal.

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

Algorithm

To solve this problem, we will follow these steps ?

  • Find the minimum value in the list
  • Initialize sum as 0
  • For each number in the list, add the difference between that number and minimum value to the sum
  • Return the total sum

How It Works

The key insight is that instead of incrementing all other elements, we can think of it as decrementing the selected element. This means we need to bring all elements down to the minimum value in the list.

Example

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, numbers):
        min_val = min(numbers)
        operations = 0
        for num in numbers:
            operations += num - min_val
        return operations

# Test the solution
ob = Solution()
numbers = [2, 4, 5]
result = ob.solve(numbers)
print(f"Input: {numbers}")
print(f"Minimum operations required: {result}")
Input: [2, 4, 5]
Minimum operations required: 5

Step-by-Step Breakdown

For the input [2, 4, 5] ?

  • Minimum value = 2
  • Operations for element 2: 2 - 2 = 0
  • Operations for element 4: 4 - 2 = 2
  • Operations for element 5: 5 - 2 = 3
  • Total operations: 0 + 2 + 3 = 5

Alternative Implementation

We can also solve this using a more concise approach ?

def min_operations(numbers):
    min_val = min(numbers)
    return sum(num - min_val for num in numbers)

# Test the function
numbers = [2, 4, 5]
result = min_operations(numbers)
print(f"Minimum operations: {result}")
Minimum operations: 5

Conclusion

The solution works by finding the minimum element and calculating the sum of differences. This approach has O(n) time complexity and requires exactly sum(numbers) - n × min(numbers) operations to make all elements equal.

Updated on: 2026-03-25T10:50:51+05:30

587 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements