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.
1#include <iostream>
2#include <queue>
3#include <vector>
4#include <climits>
5
6using namespace std;
7
8int minimumDeviation(vector<int>& nums) {
9 priority_queue<int> maxHeap;
10 int minVal = INT_MAX;
11
12 for (int num : nums) {
13 if (num % 2) num *= 2;
14 maxHeap.push(num);
15 if (num < minVal) minVal = num;
16 }
17
18 int minDeviation = INT_MAX;
19 while (true) {
20 int maxVal = maxHeap.top();
21 maxHeap.pop();
22 minDeviation = min(minDeviation, maxVal - minVal);
23 if (maxVal % 2) break;
24
25 maxVal /= 2;
26 maxHeap.push(maxVal);
27 if (maxVal < minVal) minVal = maxVal;
28 }
29 return minDeviation;
30}
C++ version employs a priority_queue (max-heap) to dynamically monitor the maximum element of the array.
For each step, you pop the largest element, update the deviation, and potentially halve the maximum until it becomes odd, recalculating the base minimum as needed.
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.
1import java.util.*;
2
3public class MinimumDeviation {
4 public int minimumDeviation(int[] nums) {
5 for (int i = 0; i < nums.length; ++i) {
6 if (nums[i] % 2 == 1) nums[i] *= 2;
7 }
8 Arrays.sort(nums);
9 int minDeviation = nums[nums.length - 1] - nums[0];
10
11 while (nums[nums.length - 1] % 2 == 0) {
12 nums[nums.length - 1] /= 2;
13 Arrays.sort(nums);
14 minDeviation = Math.min(minDeviation, nums[nums.length - 1] - nums[0]);
15 }
16
17 return minDeviation;
18 }
19}
Java here focuses on a pure sorting and deviation methodology emphasizing direct operations over lists without additional Java-specific heap structures. Target is achieving minimal deviation by regular step reductions of maxima.