Program to find minimum operations to make array equal using Python

PythonServer Side ProgrammingProgramming

Suppose we have a value n, consider an array nums with n elements, where arr[i] = (2*i)+1 for all i. Now in one operation, we can choose two indices x and y where 0 <= x, y < n and subtract 1 from nums[x] and add 1 to nums[y]. We have to make all the elements of the array same. So if we have n we have to find the minimum number of operations required to make all the elements of nums same.

So, if the input is like n = 4, then the output will be 4 as for n the array is [1,3,5,7], now after first operation we can make array like [2,3,5,6], after second operation we can make [3,3,5,5],then after third [4,3,4,5] and finally [4,4,4,4]. So now all are equal.

To solve this, we will follow these steps −

  • ans:= 0

  • if n is same as 1, then

    • return ans

  • q:= quotient of (n/2) -1

  • j:= 1

  • while q>=0, do

    • ans:= ans + (n-j)

    • q := q - 1

    • j := j + 2

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(n):
   ans=0
   if n==1:
      return ans
   q=(n//2)-1
   j=1
   while q>=0:
      ans=ans+(n-j)
      q-=1
      j+=2
   return ans
n = 4
print(solve(n))

Input

4

Output

4
raja
Published on 28-May-2021 13:03:41
Advertisements