-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path3013.cpp
More file actions
74 lines (74 loc) · 1.76 KB
/
3013.cpp
File metadata and controls
74 lines (74 loc) · 1.76 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class SmartWindow {
private:
int k;
multiset<int> low, high;
long long lowSum = 0;
public:
SmartWindow(int k) {
this->k = k;
}
int windowSize() {
return low.size() + high.size();
}
void rebalance() {
int need = min(k, windowSize());
while (low.size() > need) {
auto it = prev(low.end());
int x = *it;
lowSum -= x;
low.erase(it);
high.insert(x);
}
while (low.size() < need && !high.empty()) {
auto it = high.begin();
int x = *it;
high.erase(it);
low.insert(x);
lowSum += x;
}
}
void add(int x) {
if (low.empty() || x <= *(low.rbegin())) {
low.insert(x);
lowSum += x;
}
else {
high.insert(x);
}
rebalance();
}
void remove(int x) {
auto it = low.find(x);
if (it != low.end()) {
low.erase(it);
lowSum -= x;
}
else {
it = high.find(x);
if (it != high.end()) {
high.erase(it);
}
}
rebalance();
}
long long query() {
return lowSum;
}
};
class Solution {
public:
long long minimumCost(vector<int>& nums, int k, int dist) {
SmartWindow *window = new SmartWindow(k - 1);
int n = nums.size();
for (int i = 1; i <= 1 + dist; ++i) {
window->add(nums[i]);
}
long long res = window->query();
for (int i = 2; i + dist < n; ++i) {
window->remove(nums[i - 1]);
window->add(nums[i + dist]);
res = min(res, window->query());
}
return res + nums[0];
}
};