class SpecialAverage {
constructor(nvalue, kvalue) {
this
.left =
new
Set();
this
.mid =
new
Set();
this
.right =
new
Set();
this
.n = nvalue;
this
.k = kvalue;
this
.pos = 0;
this
.sum = 0;
this
.v =
new
Array(nvalue).fill(0);
}
add(num) {
this
.left.add(num);
if
(
this
.left.size >
this
.k) {
let temp = Math.max(...
this
.left);
this
.mid.add(temp);
this
.sum += temp;
this
.left.
delete
(temp);
}
if
(
this
.mid.size >
this
.n - 2 *
this
.k) {
let temp = Math.max(...
this
.mid);
this
.right.add(temp);
this
.sum -= temp;
this
.mid.
delete
(temp);
}
}
remove(ele) {
if
(ele <= Math.max(...
this
.left, Number.NEGATIVE_INFINITY)) {
this
.left.
delete
(ele);
}
else
if
(ele <= Math.max(...
this
.mid, Number.NEGATIVE_INFINITY)) {
this
.sum -= ele;
this
.mid.
delete
(ele);
}
else
{
this
.right.
delete
(ele);
}
if
(
this
.left.size <
this
.k) {
let temp = Math.min(...
this
.mid, Number.POSITIVE_INFINITY);
this
.left.add(temp);
this
.sum -= temp;
this
.mid.
delete
(temp);
}
if
(
this
.mid.size <
this
.n - 2 *
this
.k) {
let temp = Math.min(...
this
.right, Number.POSITIVE_INFINITY);
this
.mid.add(temp);
this
.sum += temp;
this
.right.
delete
(temp);
}
}
addInteger(num) {
if
(
this
.pos >=
this
.n) {
this
.remove(
this
.v[
this
.pos %
this
.n]);
}
this
.v[
this
.pos %
this
.n] = num;
this
.add(num);
this
.pos++;
}
calculateSpecialAverage() {
if
(
this
.pos >=
this
.n) {
return
Math.floor(
this
.sum / (
this
.n - 2 *
this
.k));
}
return
-1;
}
}
function
processQueries(n, k) {
let avg =
new
SpecialAverage(n, k);
avg.addInteger(4);
avg.addInteger(2);
console.log(avg.calculateSpecialAverage());
avg.addInteger(10);
console.log(avg.calculateSpecialAverage());
}
const N = 3;
const K = 1;
processQueries(N, K);