|
| 1 | +class MKAverage { |
| 2 | + int m,k; |
| 3 | + multiset<int>Set1; |
| 4 | + multiset<int>Set2; |
| 5 | + multiset<int>Set3; |
| 6 | + long sum = 0; |
| 7 | + queue<int>q; |
| 8 | + vector<int>temp; |
| 9 | +public: |
| 10 | + MKAverage(int m, int k) |
| 11 | + { |
| 12 | + this->m = m; |
| 13 | + this->k = k; |
| 14 | + } |
| 15 | + |
| 16 | + void addElement(int num) |
| 17 | + { |
| 18 | + q.push(num); |
| 19 | + temp.push_back(num); |
| 20 | + |
| 21 | + if (q.size() == m) |
| 22 | + { |
| 23 | + sort(temp.begin(), temp.end()); |
| 24 | + for (int i=0; i<k; i++) |
| 25 | + Set1.insert(temp[i]); |
| 26 | + for (int i=k; i<m-k; i++) |
| 27 | + { |
| 28 | + Set2.insert(temp[i]); |
| 29 | + sum += temp[i]; |
| 30 | + } |
| 31 | + for (int i=m-k; i<m; i++) |
| 32 | + Set3.insert(temp[i]); |
| 33 | + } |
| 34 | + else if (q.size() == m+1) |
| 35 | + { |
| 36 | + int x = q.front(); |
| 37 | + q.pop(); |
| 38 | + |
| 39 | + // delete the old element |
| 40 | + if (Set1.find(x)!=Set1.end()) |
| 41 | + Set1.erase(Set1.lower_bound(x)); |
| 42 | + else if (Set3.find(x)!=Set3.end()) |
| 43 | + Set3.erase(Set3.lower_bound(x)); |
| 44 | + else |
| 45 | + { |
| 46 | + Set2.erase(Set2.lower_bound(x)); |
| 47 | + sum -= x; |
| 48 | + } |
| 49 | + |
| 50 | + // add the new element |
| 51 | + if (!Set1.empty() && num <= *Set1.rbegin()) |
| 52 | + Set1.insert(num); |
| 53 | + else if (!Set3.empty() && num >= *Set3.begin()) |
| 54 | + Set3.insert(num); |
| 55 | + else |
| 56 | + { |
| 57 | + Set2.insert(num); |
| 58 | + sum += num; |
| 59 | + } |
| 60 | + |
| 61 | + // adjust the three sets |
| 62 | + while (Set1.size() > k) |
| 63 | + { |
| 64 | + int y = *Set1.rbegin(); |
| 65 | + Set1.erase(Set1.lower_bound(y)); |
| 66 | + Set2.insert(y); |
| 67 | + sum += y; |
| 68 | + } |
| 69 | + while (Set3.size() > k) |
| 70 | + { |
| 71 | + int y = *Set3.begin(); |
| 72 | + Set3.erase(Set3.lower_bound(y)); |
| 73 | + Set2.insert(y); |
| 74 | + sum += y; |
| 75 | + } |
| 76 | + |
| 77 | + while (Set1.size() < k) |
| 78 | + { |
| 79 | + int y = *Set2.begin(); |
| 80 | + Set2.erase(Set2.lower_bound(y)); |
| 81 | + Set1.insert(y); |
| 82 | + sum -= y; |
| 83 | + } |
| 84 | + while (Set3.size() < k) |
| 85 | + { |
| 86 | + int y = *Set2.rbegin(); |
| 87 | + Set2.erase(Set2.lower_bound(y)); |
| 88 | + Set3.insert(y); |
| 89 | + sum -= y; |
| 90 | + } |
| 91 | + } |
| 92 | + } |
| 93 | + |
| 94 | + int calculateMKAverage() |
| 95 | + { |
| 96 | + if (q.size() < m) |
| 97 | + return -1; |
| 98 | + else |
| 99 | + return sum / (m-2*k); |
| 100 | + } |
| 101 | +}; |
| 102 | + |
| 103 | +/** |
| 104 | + * Your MKAverage object will be instantiated and called as such: |
| 105 | + * MKAverage* obj = new MKAverage(m, k); |
| 106 | + * obj->addElement(num); |
| 107 | + * int param_2 = obj->calculateMKAverage(); |
| 108 | + */ |
| 109 | + |
0 commit comments