Greedy Case Work | Java | C++
Intuition, approach, and complexity discussed in video solution in detail\nhttps://youtu.be/xEPTygm6rdI\n\n# Code\nJava\n\nclass Solution {\n    public int minD
# Intuition, approach, and complexity discussed in video solution in detail\nhttps://youtu.be/xEPTygm6rdI\n\n# Code\nJava\n```\nclass Solution {\n    public int minDifference(int[] nums) {\n        int size = nums.length;\n        if (size <= 4) {\n            return 0;\n        }\n        PriorityQueue<Integer> minHeap = new PriorityQueue<>();\n        PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b)->(b - a));\n        for (var num : nums) {\n            maxHeap.offer(num);\n            if (maxHeap.size() > 4) {\n                maxHeap.poll();\n            }\n            minHeap.offer(num);\n            if (minHeap.size() > 4) {\n                minHeap.poll();\n            }\n        }\n        List<Integer> minFour = new ArrayList<>(maxHeap);\n        List<Integer> maxFour = new ArrayList<>(minHeap);\n        Collections.sort(minFour);\n        Collections.sort(maxFour);\n        int minDif = Integer.MAX_VALUE;\n        for (int indx = 0; indx < 4; indx++) {\n            int currDiff = maxFour.get(indx) - minFour.get(indx);\n            minDif = Math.min(minDif, currDiff);\n        }\n        return minDif;\n    }\n}\n```\nC++\n```\nclass Solution {\npublic:\n    int minDifference(vector<int>& nums) {\n        int size = nums.size();\n        if (size <= 4) {\n            return 0;\n        }\n        \n        priority_queue<int, vector<int>, greater<int>> minHeap;\n        priority_queue<int> maxHeap;\n        \n        for (int num : nums) {\n            maxHeap.push(num);\n            if (maxHeap.size() > 4) {\n                maxHeap.pop();\n            }\n            minHeap.push(num);\n            if (minHeap.size() > 4) {\n                minHeap.pop();\n            }\n        }\n        \n        vector<int> minFour, maxFour;\n        while (!maxHeap.empty()) {\n            minFour.push_back(maxHeap.top());\n            maxHeap.pop();\n        }\n        while (!minHeap.empty()) {\n            maxFour.push_back(minHeap.top());\n            minHeap.pop();\n        }\n        \n        sort(minFour.begin(), minFour.end());\n        sort(maxFour.begin(), maxFour.end());\n        \n        int minDif = INT_MAX;\n        for (int indx = 0; indx < 4; ++indx) {\n            int currDiff = maxFour[indx] - minFour[indx];\n            minDif = min(minDif, currDiff);\n        }\n        \n        return minDif;\n    }\n};\n\n```
['Array', 'Greedy', 'C++', 'Java']