1509. Minimum Difference Between Largest and Smallest Value in Three Moves
You are given an integer array nums. In one move, you can choose one element of nums and change it by any value.
Return the minimum difference between the largest and smallest value of nums after performing at most three moves.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| class Solution { int heapSolution(vector<int>& nums) { priority_queue<int, vector<int>, greater<int>> minHeap; priority_queue<int> maxHeap; for(int i = 0; i < nums.size(); i++) { minHeap.push(nums[i]); maxHeap.push(nums[i]); if(maxHeap.size() >= 5) maxHeap.pop(); if(minHeap.size() >= 5) minHeap.pop(); } vector<int> n; while(!minHeap.empty()) { n.push_back(minHeap.top()); minHeap.pop(); } while(!maxHeap.empty()) { n.push_back(maxHeap.top()); maxHeap.pop(); } sort(n.begin(), n.end()); return slidingWindow(n); } int slidingWindow(vector<int>& nums) { int res = INT_MAX; for(int l = 0, r = nums.size() - 4; l < 4; l++,r++) { res = min(res, nums[r] - nums[l]); } return res; } public: int minDifference(vector<int>& nums) { if(nums.size() <= 4) return 0; if(nums.size() >= 8) return heapSolution(nums); sort(nums.begin(), nums.end()); return slidingWindow(nums); } };
|