#1675
Minimize Deviation in Array
HardArrayGreedyHeap (Priority Queue)Ordered SetHeap (Priority Queue)Greedy Algorithms
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a max-heap to efficiently track the maximum value while minimizing the deviation. By always halving the largest even number, we can ensure that we are reducing the maximum value while keeping track of the minimum value.
⚙️
Algorithm
4 steps- 1Step 1: Convert all numbers to even by multiplying odd numbers by 2.
- 2Step 2: Use a max-heap to keep track of the maximum value in the array.
- 3Step 3: Continuously remove the maximum value, halve it, and reinsert it into the heap until it becomes odd.
- 4Step 4: Calculate the current deviation and update the minimum deviation found.
solution.py20 lines
1import heapq
2
3def min_deviation(nums):
4 max_heap = []
5 min_val = float('inf')
6 for num in nums:
7 if num % 2 != 0:
8 num *= 2
9 heapq.heappush(max_heap, -num)
10 min_val = min(min_val, num)
11 min_deviation = float('inf')
12 while max_heap:
13 max_val = -heapq.heappop(max_heap)
14 min_deviation = min(min_deviation, max_val - min_val)
15 if max_val % 2 == 0:
16 heapq.heappush(max_heap, -max_val // 2)
17 min_val = min(min_val, max_val // 2)
18 else:
19 break
20 return min_deviationℹ
Complexity note: The time complexity is O(n log n) due to the operations on the max-heap, where n is the number of elements in the array. The space complexity is O(n) for storing the elements in the heap.
- 1The operations allowed on the array elements can significantly change their values, thus affecting the deviation.
- 2Using a max-heap allows us to efficiently manage the maximum value while minimizing the deviation.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.