1825. Finding MK Average.cpp
Code\n\nclass MKAverage {\npublic:\n    set<pair<int, int>, greater<>>MaxHeap;\n    set<pair<int, int>>MinHeap;\n    set<pair<int, int>>MidHeap;\n    queue<int>
**Code**\n```\nclass MKAverage {\npublic:\n    set<pair<int, int>, greater<>>MaxHeap;\n    set<pair<int, int>>MinHeap;\n    set<pair<int, int>>MidHeap;\n    queue<int>vals;\n    int M, K;\n    int count;\n    long long Sum;\n    int midLength;\n    MKAverage(int m, int k) {\n        M = m;\n        K = k;\n        Sum = 0L;\n        count = 0;\n        midLength = M - 2 * K;\n    }\n    void addElement(int num) {\n        count++;\n        vals.push(num);\n        if (count > M)\n        {\n            pair<int, int> target = { vals.front(),count - M };\n            vals.pop();\n            if (MaxHeap.find(target) != MaxHeap.end())\n            {\n                MaxHeap.erase(target);\n                MaxHeap.insert(*MidHeap.begin());\n                Sum -= (*MidHeap.begin()).first;\n                MidHeap.erase(MidHeap.begin());\n            }\n            else if (MinHeap.find(target) != MinHeap.end())\n            {\n                MinHeap.erase(target);\n                MinHeap.insert(*MidHeap.rbegin());\n                Sum -= (*MidHeap.rbegin()).first;\n                MidHeap.erase(*MidHeap.rbegin());\n            }           \n            else\n            {\n                Sum -= target.first;\n                MidHeap.erase(MidHeap.find(target));\n            }\n        }\n        MaxHeap.insert({ num,count });\n        if (MaxHeap.size() > K)\n        {\n            auto maxVal = *MaxHeap.begin();\n            MaxHeap.erase(MaxHeap.begin());\n            MinHeap.insert(maxVal);           \n            if (MinHeap.size() > K)\n            {\n                auto minVal = *MinHeap.begin();\n                MinHeap.erase(MinHeap.begin());\n                MidHeap.insert(minVal);\n                Sum += minVal.first;\n            }\n        }\n\n    }\n    int calculateMKAverage() {\n        if (count < M) return -1;\n        else return Sum / midLength;\n    }\n};\n```
['C']