Untitled

mail@pastecode.io avatar
unknown
plain_text
18 days ago
562 B
3
Indexable
Never
class Solution {
public:
    int minDifference(vector<int>& nums) {
        int n = nums.size(), ans = INT_MAX;
        
        if (n < 5) return 0;

        partial_sort(nums.begin(), nums.begin() + 4, nums.end());

        nth_element(nums.begin() + 4, nums.begin() + (n - 4),
                    nums.end());

        sort(nums.begin() + (n - 4), nums.end());
        
        int right = n - 4;

        for (int left = 0; left < 4; left++) {
            ans = min(ans, nums[right] - nums[left]);
            right++;
        }

        return ans;
    }
};
Leave a Comment