Approach
Given a solution [ group A ] [i1 .. ] .. [ .. ] [i(k-1)], the distance between i1 and i(k-1)should be smaller then dist, and we assume that now the group A is fixed. The problem now is that we need to findk-2minimum elements in the range[i1 .. i(k-1)](excludingi1` itself), this part is similar to previous daily.
Now we tried to do a sliding window, and we the current score is the first element of group A, plus the first element within the sliding window (dist+1 wide), and the sum of k-2 minimum value inside that sliding window (exlude the first one). We maintain the best score and we get the answer after sliding window.
The problem now is that how do we efficiently get the minimum k-2 number’s sum within the sliding window. I use two multiset to do this, we check the value for removed valud and the inserted valud, incremetally upate two multiset to ensure that hte first multiset has the minimum elements, also we can incremantally update the accumluated value, and this can be done in O(lgN) time.
Code
class Solution {
public:
long long minimumCost(vector<int>& nums, int k, int dist) {
int n = nums.size();
int idx = 1;
vector<int> group;
group.reserve(n);
for(int i = idx+1 ; i <= idx+dist ; ++i) {
group.push_back(nums[i]);
}
sort(group.begin(), group.end());
long long accum = accumulate(group.begin(), group.begin() + k-2, (long long)0);
multiset<int> ms1;
multiset<int> ms2;
for(int i = 0 ; i < group.size() ; ++i) {
if(i < k-2) ms1.insert(group[i]);
else ms2.insert(group[i]);
}
long long minScore = nums[0] + nums[1] + accum;
idx = 2; // [idx .. idx+dist]
while(idx+(k-2) < n) {
int removeVal = nums[idx];
int newIdx = idx+dist;
int newVal = (newIdx >= n) ? INT_MAX : nums[newIdx];
auto it2 = ms2.find(removeVal);
if(it2 != ms2.end()) {
ms2.erase(it2);
auto hi = prev(ms1.end());
if(*hi > newVal) {
ms1.insert(newVal);
accum += newVal;
ms2.insert(*hi);
accum -= *hi;
ms1.erase(hi);
} else {
ms2.insert(newVal);
}
} else {
auto it = ms1.find(removeVal);
ms1.erase(it);
accum -= removeVal;
ms2.insert(newVal);
auto lo = ms2.begin();
ms1.insert(*lo);
accum += *lo;
ms2.erase(lo);
}
minScore = min(minScore, (long long)nums[0] + nums[idx] + accum);
++idx;
}
return minScore;
}
};