Number of operations required to make all array elements Equal in Python

PythonServer Side ProgrammingProgramming

We have given an array of elements, and we have to make them all equal by incrementing the elements by 1. We are allowed to increment n - 1 element at each step. Our goal is to calculate the total number of operations required to make all the array elements equal.

For example, if you take the list [1, 2, 3], it took three operations to make all the elements equal. One solution to the problem is. Find the most significant number at each step and increment the rest of the elements by 1. Let's write the code.

Example

 Live Demo

def main():
   # intializing the array
   arr = [1, 2, 3]
   # initializing operations count to 0
   no_of_operations = 0
   flag = 0
   # performing the operations on array to make them equal
   while not are_equal(arr):
      flag = 1
      # finding the maximum from the list
      maximum = max(arr)
      # incrementing all the elements except maximum
      for i in range(len(arr)):
         if arr[i] != maximum:
            arr[i] += 1
      # incrementing the operations count by 1
      no_of_operations += 1
   print(no_of_operations) if flag == 0 else print(no_of_operations + 1)
# checking whether all the elements are equal or not
def are_equal(arr):
   global no_of_operations
   for i in range(len(arr) - 1):
      if arr[i] != arr[i + 1]:
         return False
   return True
if __name__ == '__main__':
   main()

Output

If you run the above program, you will get the following results.

3

The above method takes more time to compute for large arrays. We can find the number of operations by finding the sum and the smallest element of the array.

  • Find the sum of the array.
  • Find the smallest of all elements in the array.
  • Print the value get from the expression sum - (length - smallest).

Example

See the code below.

 Live Demo

# initializing an array
arr = [1, 2, 3]
# length
length = len(arr)
# sum of element fo the array
elements_sum = sum(arr)
# smallest among all the elements
smallest = min(arr)
# calculating the number of operations
print(elements_sum - (length * smallest))

Output

If you run the above code, you will get the following results.

3

Conclusion

The second method that we discussed is easier and takes less time compared to the first method. If you have any doubts in the tutorial, mention them in the comment section.

raja
Published on 02-Jan-2020 10:38:17
Advertisements