Program to minimize deviation in array in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums. We can perform two types of operations on any element of the array any number of times

  • For even elements, divide it by 2

  • For odd elements, multiply it by 2.

Now the deviation of the array is the maximum difference between any two elements in the array. We have to find the minimum deviation the array can have after performing some number of operations. So, if the input is like nums = [6,3,7,22,5], then the output will be 5 because we can make our array in one operation [6,6,7,22,5] and in second operation [6,6,7,22,10], and in another operation [6,6,7,11,10], now the deviation is 11-6 = 5.

To solve this, we will follow these steps −

  • sort the list nums

  • max_v := maximum element of nums

  • min_v := minimum element of nums

  • heapify nums

  • res := max_v - min_v

  • while nums[0] is odd, do

    • v := poped element from heap queue nums

    • v := 2 * v

    • insert v into heap queue nums

    • min_v := nums[0]

    • max_v := maximum of v and max_v

    • res := minimum of res and (max_v - min_v)

  • nums := a list of all numbers in n and in negative order

  • heapify heap queue nums

  • while nums[0] is even, do

    • v := -(poped element from heap queue nums)

    • v := quotient of (v/2)

    • insert -v into the heap queue nums

    • max_v := -nums[0]

    • min_v := minimum of min_v and v

    • res := minimum of res and (max_v - min_v)

  • return res

Example

Let us see the following implementation to get better understanding

import heapq
def solve(nums):
   nums.sort()
   max_v,min_v = nums[-1],nums[0]
   heapq.heapify(nums)
   res = max_v-min_v
   while nums[0]%2==1:
      v = heapq.heappop(nums)
      v = 2 * v
      heapq.heappush(nums, v)
      min_v = nums[0]
      max_v = max(v, max_v)
      res = min(res, max_v - min_v)

   nums = [-n for n in nums]
   heapq.heapify(nums)
   while nums[0]%2==0:
      v = -heapq.heappop(nums)
      v = v // 2
      heapq.heappush(nums, -v)
      max_v = -nums[0]
      min_v = min(min_v,v)
      res = min(res, max_v - min_v)

   return res

nums = [6,3,7,22,5]
print(solve(nums))

Input

[6,3,7,22,5]

Output

5
raja
Published on 07-Oct-2021 07:54:25
Advertisements