[LeetCode] Minimum Difference Between Largest and Smallest Value in Three Moves

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) { //o(nlog5)
priority_queue<int, vector<int>, greater<int>> minHeap; //has max value
priority_queue<int> maxHeap; //has min value

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; //we can change all values;
if(nums.size() >= 8) return heapSolution(nums);
sort(nums.begin(), nums.end()); //o(nlogn)
return slidingWindow(nums);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/18/PS/LeetCode/minimum-difference-between-largest-and-smallest-value-in-three-moves/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.