Skip to content

1675. Minimize Deviation in Array 👍

  • Time: $O(\log\max(\texttt{nums}) \cdot n\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int minimumDeviation(vector<int>& nums) {
    int ans = INT_MAX;
    int mn = INT_MAX;
    priority_queue<int> maxHeap;

    for (const int num : nums) {
      const int evenNum = num % 2 == 0 ? num : num * 2;
      mn = min(mn, evenNum);
      maxHeap.push(evenNum);
    }

    while (maxHeap.top() % 2 == 0) {
      const int mx = maxHeap.top();
      maxHeap.pop();
      ans = min(ans, mx - mn);
      mn = min(mn, mx / 2);
      maxHeap.push(mx / 2);
    }

    return min(ans, maxHeap.top() - mn);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int minimumDeviation(int[] nums) {
    int ans = Integer.MAX_VALUE;
    int mn = Integer.MAX_VALUE;
    Queue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());

    for (final int num : nums) {
      final int evenNum = num % 2 == 0 ? num : num * 2;
      mn = Math.min(mn, evenNum);
      maxHeap.offer(evenNum);
    }

    while (maxHeap.peek() % 2 == 0) {
      final int mx = maxHeap.poll();
      ans = Math.min(ans, mx - mn);
      mn = Math.min(mn, mx / 2);
      maxHeap.offer(mx / 2);
    }

    return Math.min(ans, maxHeap.peek() - mn);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def minimumDeviation(self, nums: list[int]) -> int:
    ans = math.inf
    mn = math.inf
    maxHeap = []

    for num in nums:
      evenNum = num if num % 2 == 0 else num * 2
      heapq.heappush(maxHeap, -evenNum)
      mn = min(mn, evenNum)

    while maxHeap[0] % 2 == 0:
      mx = -heapq.heappop(maxHeap)
      ans = min(ans, mx - mn)
      mn = min(mn, mx // 2)
      heapq.heappush(maxHeap, -mx // 2)

    return min(ans, -maxHeap[0] - mn)