File tree Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Expand file tree Collapse file tree 1 file changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: ctor: O(1)
2
+ // add_element: O(logn)
3
+ // calc_mkaverage: O(1)
4
+ // Space: O(m)
5
+
6
+ class MKAverage {
7
+ public:
8
+ MKAverage (int m, int k)
9
+ : m_{m}
10
+ , k_{k} {
11
+
12
+ }
13
+
14
+ void addElement (int num) {
15
+ if (size (dq_) == m_) {
16
+ remove (dq_.front ());
17
+ dq_.pop_front ();
18
+ }
19
+ dq_.emplace_back (num);
20
+ add (num);
21
+ }
22
+
23
+ int calculateMKAverage () {
24
+ if (size (dq_) < m_) {
25
+ return -1 ;
26
+ }
27
+ return total_ / (m_ - 2 * k_);
28
+ }
29
+
30
+ private:
31
+ void add (int num) {
32
+ left_.emplace (num);
33
+ if (size (left_) > k_) {
34
+ const auto it = prev (end (left_));
35
+ mid_.emplace (*it);
36
+ total_ += *it;
37
+ left_.erase (it);
38
+ }
39
+ if (size (mid_) > (m_ - 2 * k_)) {
40
+ const auto it = prev (end (mid_));
41
+ total_ -= *it;
42
+ right_.emplace (*it);
43
+ mid_.erase (it);
44
+ }
45
+ }
46
+
47
+ void remove (int num) {
48
+ if (num <= *rbegin (left_)) {
49
+ left_.erase (left_.find (num));
50
+ } else if (num <= *rbegin (mid_)) {
51
+ auto it = mid_.find (num);
52
+ total_ -= *it;
53
+ mid_.erase (it);
54
+ } else {
55
+ right_.erase (right_.find (num));
56
+ }
57
+ if (size (left_) < k_) {
58
+ left_.emplace (*begin (mid_));
59
+ total_ -= *begin (mid_);
60
+ mid_.erase (begin (mid_));
61
+ }
62
+ if (size (mid_) < (m_ - 2 * k_)) {
63
+ mid_.emplace (*begin (right_));
64
+ total_ += *begin (right_);
65
+ right_.erase (begin (right_));
66
+ }
67
+ }
68
+
69
+ int m_;
70
+ int k_;
71
+ deque<int > dq_;
72
+ multiset<int > left_, mid_, right_;
73
+ int64_t total_ = 0 ;
74
+ };
You can’t perform that action at this time.
0 commit comments