1794. Minimize Deviation in Array
My accepted Python solution to LeetCode problem 1794, Minimize Deviation in Array, running in 1038ms.
- Difficulty: Hard
- Python
- Runtime 1038ms
- Memory 24.6MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 1038ms, memory 24.6MB, accepted 2026-01-01.
class Solution:
def minimumDeviation(self, nums: List[int]) -> int:
import heapq
# First, multiply all odd numbers by 2 to make them even
# This way, we can only decrease numbers (divide by 2)
# Use max heap (negate values for min heap)
heap = []
min_val = float('inf')
for num in nums:
if num % 2 == 1:
num *= 2
heapq.heappush(heap, -num)
min_val = min(min_val, num)
result = -heap[0] - min_val
# Keep dividing the maximum element by 2 if it's even
while heap[0] % 2 == 0: # heap[0] is negative, so check if even
max_val = -heapq.heappop(heap)
max_val //= 2
min_val = min(min_val, max_val)
heapq.heappush(heap, -max_val)
result = min(result, -heap[0] - min_val)
return result