|
| 1 | +/** |
| 2 | + * 1675. Minimize Deviation in Array |
| 3 | + * https://leetcode.com/problems/minimize-deviation-in-array/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given an array nums of n positive integers. |
| 7 | + * |
| 8 | + * You can perform two types of operations on any element of the array any number of times: |
| 9 | + * - If the element is even, divide it by 2. |
| 10 | + * - For example, if the array is [1,2,3,4], then you can do this operation on the last element, |
| 11 | + * and the array will be [1,2,3,2]. |
| 12 | + * - If the element is odd, multiply it by 2. |
| 13 | + * - For example, if the array is [1,2,3,4], then you can do this operation on the first element, |
| 14 | + * and the array will be [2,2,3,4]. |
| 15 | + * |
| 16 | + * The deviation of the array is the maximum difference between any two elements in the array. |
| 17 | + * |
| 18 | + * Return the minimum deviation the array can have after performing some number of operations. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number[]} nums |
| 23 | + * @return {number} |
| 24 | + */ |
| 25 | +var minimumDeviation = function(nums) { |
| 26 | + const heap = []; |
| 27 | + let minElement = Infinity; |
| 28 | + |
| 29 | + for (const num of nums) { |
| 30 | + const value = num % 2 ? num * 2 : num; |
| 31 | + heap.push(value); |
| 32 | + minElement = Math.min(minElement, value); |
| 33 | + } |
| 34 | + |
| 35 | + for (let i = Math.floor(heap.length / 2) - 1; i >= 0; i--) { |
| 36 | + siftDown(i); |
| 37 | + } |
| 38 | + |
| 39 | + let minDeviation = heap[0] - minElement; |
| 40 | + |
| 41 | + while (heap[0] % 2 === 0) { |
| 42 | + const maxElement = heap[0]; |
| 43 | + heap[0] = maxElement / 2; |
| 44 | + minElement = Math.min(minElement, heap[0]); |
| 45 | + siftDown(0); |
| 46 | + minDeviation = Math.min(minDeviation, heap[0] - minElement); |
| 47 | + } |
| 48 | + |
| 49 | + return minDeviation; |
| 50 | + |
| 51 | + function siftDown(index) { |
| 52 | + while (2 * index + 1 < heap.length) { |
| 53 | + let maxChild = 2 * index + 1; |
| 54 | + if (maxChild + 1 < heap.length && heap[maxChild + 1] > heap[maxChild]) { |
| 55 | + maxChild++; |
| 56 | + } |
| 57 | + if (heap[index] < heap[maxChild]) { |
| 58 | + [heap[index], heap[maxChild]] = [heap[maxChild], heap[index]]; |
| 59 | + index = maxChild; |
| 60 | + } else { |
| 61 | + break; |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +}; |
0 commit comments