Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to minimize deviation in array in Python
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.
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.
Algorithm
To solve this, we will follow these steps ?
Sort the array and initialize min and max values
Use a min heap to process odd numbers (multiply by 2)
Convert to max heap (using negative values) to process even numbers (divide by 2)
Track the minimum deviation throughout the process
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
# Process odd numbers (multiply by 2)
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)
# Convert to max heap for processing even numbers
nums = [-n for n in nums]
heapq.heapify(nums)
# Process even numbers (divide by 2)
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))
5
How It Works
The algorithm works in two phases ?
Phase 1: Use a min heap to multiply all odd numbers by 2 until no odd numbers remain at the minimum position
Phase 2: Convert to a max heap and divide even numbers by 2 to minimize the maximum value
The key insight is that we can only increase odd numbers and decrease even numbers, so we systematically explore both directions to find the minimum possible deviation.
Conclusion
This solution uses a two−phase approach with heaps to minimize array deviation. The algorithm efficiently explores all possible transformations by first increasing odd numbers, then decreasing even numbers to achieve the minimum deviation.
