Minimize Deviation in Array Problem
Description
LeetCode Problem 1675.
You are given an array nums of n positive integers.
You can perform two types of operations on any element of the array any number of times:
- If the element is even, divide it by
2.- For example, if the array is
[1,2,3,4], then you can do this operation on the last element, and the array will be[1,2,3,2].
- For example, if the array is
- If the element is odd, multiply it by
2.- For example, if the array is
[1,2,3,4], then you can do this operation on the first element, and the array will be[2,2,3,4].
- For example, if the array is
The deviation of the array is the maximum difference between any two elements in the array.
Return the minimum deviation the array can have after performing some number of operations.
Example 1:
Input: nums = [1,2,3,4]
Output: 1
Explanation: You can transform the array to [1,2,3,2], then to [2,2,3,2], then the deviation will be 3 - 2 = 1.
Example 2:
Input: nums = [4,1,5,20,3]
Output: 3
Explanation: You can transform the array after two operations to [4,2,5,5,3], then the deviation will be 5 - 2 = 3.
Example 3:
Input: nums = [2,10,8]
Output: 3
Constraints:
n == nums.length2 <= n <= 5 * 10^41 <= nums[i] <= 10^9
Solution
Approach: Max-Heap, Shrinking the Largest Value
An odd number can be doubled only once (it becomes even), while an even number can be halved until it turns odd. So first double every odd number: now every value is at its largest possible value, and the only remaining move is halving an even number.
The deviation is max - min. Increasing the minimum is no longer possible, so the only useful move is to halve the current maximum, and only while it is even. Keep all values in a max-heap and track the current minimum:
- Record
max - minas a candidate answer. - If the maximum is odd, stop: it can never get smaller.
- Otherwise pop it, push half of it, and update the minimum with that half.
The smallest candidate seen is the answer.
Complexity: each value is halved at most O(log M) times, where M is the largest value, so O(n log n log M) time in total; O(n) extra space for the heap.
from heapq import heapify, heappop, heappush
from math import inf
class Solution:
def minimumDeviation(self, nums: List[int]) -> int:
h = []
mi = inf
for v in nums:
if v & 1:
v <<= 1
h.append(-v)
mi = min(mi, v)
heapify(h)
ans = -h[0] - mi
while h[0] % 2 == 0:
x = heappop(h) // 2
heappush(h, x)
mi = min(mi, -x)
ans = min(ans, -h[0] - mi)
return ans