This approach utilizes a max-heap to efficiently retrieve the largest element while adjusting it within the array to reduce deviation.
1. First, we convert all numbers to even (since an odd number can only become larger when even via multiplication). This is done by multiplying odd numbers by 2.
2. We utilize a max-heap where each iteration involves reducing the maximum number (if even) to reduce the deviation.
3. Throughout this process, track the minimum seen number to calculate and update the minimum deviation at every stage.
Time Complexity: O(n log n) due to sorting operations on each iteration.
Space Complexity: O(n) for the heap structure representation.
1import heapq
2
3class Solution:
4 def minimumDeviation(self, nums):
5 heap = []
6 min_val = float('inf')
7
8 for num in nums:
9 if num % 2:
10 num *= 2
11 heapq.heappush(heap, -num) # Python min-heap inverts the number to simulate a max-heap
12 min_val = min(min_val, num)
13
14 min_deviation = float('inf')
15
16 while heap:
17 max_val = -heapq.heappop(heap)
18 min_deviation = min(min_deviation, max_val - min_val)
19 if max_val % 2:
20 break
21 max_val //= 2
22 min_val = min(min_val, max_val)
23 heapq.heappush(heap, -max_val)
24
25 return min_deviation
The Python approach uses the heapq
module to construct a max-heap by inversing values (using negation).
It iteratively removes the highest number, adjusts its value, and manages updates of the deviation/minimum value each cycle.
In this alternative approach, the strategy focuses on an incremental adjustment instead of heap reliance. It involves directly mutating and managing the adjustment in a sorted sequence approach to target deviation reduction without standard heap operations.
1. First, transform any odd number by doubling it. Track the preliminary minimum number.
2. Sort the array and iteratively adjust the maximum through division by halving until reaching an odd number.
The minimum deviation is kept through direct comparison evaluations across the deviations achieved after each max adjustment.
Time Complexity: O(n^2 log n) due to multiple sorts.
Space Complexity: O(1) or O(n) considering in-place sorts might not require extra space.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4
5using namespace std;
6
7int minimumDeviation(vector<int>& nums) {
8 for (auto &num : nums)
9 if (num % 2 == 1) num *= 2;
10
11 sort(nums.begin(), nums.end());
12 int minDeviation = nums.back() - nums.front();
13
14 while (nums.back() % 2 == 0) {
15 nums.back() /= 2;
16 sort(nums.begin(), nums.end());
17 minDeviation = min(minDeviation, nums.back() - nums.front());
18 }
19
20 return minDeviation;
21}
This C++ method establishes deviation reduction by direct manipulation within a sorting framework, enhancing deviation tracking without reliance on a priority queue.
It leverages basic direct list sorting after direct maximal element alterations.