Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

1675. Minimize Deviation in Array 🌟🌟🌟

You are given an array nums of n positive integers.

You can perform two types of operations on any element of the array any number of times:

The deviation of the array is the maximum difference between any two elements in the array.

Return the minimum deviation the array can have after performing some number of operations.

Priority Queue (AC)

Code

class Solution {
public:
    int minimumDeviation(vector<int>& nums)
    {
        int n = nums.size();
        int mx = INT_MIN, mn = INT_MAX;

        // Increase the odd numbers to its maximum value which is num*2 & track min,max num.
        for (int i = 0; i < n; ++i) {
            if ((nums[i] % 2) & 1)
                nums[i] *= 2;
            mx = max(mx, nums[i]);
            mn = min(mn, nums[i]);
        }
        int minDev = mx - mn;

        priority_queue<int> pq;
        // Inserting nums Priority queue (Max Heap)
        for (int i = 0; i < n; i++) {
            pq.push(nums[i]);
        }

        while (((pq.top()) & 1) == 0) {
            int topNum = pq.top();
            pq.pop(); // popped the top element

            minDev = min(minDev, topNum - mn);
            topNum /= 2;
            mn = min(mn, topNum); // updating min
            pq.push(topNum); // pushing again the top as we have to minimize the max
        }

        minDev = min(minDev, pq.top() - mn);

        return minDev;
    }
};

Set

Code

// <!-- TODO: Code here -->

Must Read