function
countElements(R, N, arr) {
let heap =
new
PriorityQueue();
for
(let i = 0; i < R; i++) {
heap.add(arr[i]);
}
for
(let i = R; i < N; i++) {
if
(arr[i] > heap.peek()) {
heap.poll();
heap.add(arr[i]);
}
}
return
heap.size();
}
class PriorityQueue {
constructor() {
this
.heap = [];
}
add(val) {
this
.heap.push(val);
this
.bubbleUp(
this
.heap.length - 1);
}
poll() {
if
(
this
.heap.length === 0) {
return
null
;
}
const min =
this
.heap[0];
const last =
this
.heap.pop();
if
(
this
.heap.length > 0) {
this
.heap[0] = last;
this
.bubbleDown(0);
}
return
min;
}
peek() {
return
this
.heap.length > 0 ?
this
.heap[0] :
null
;
}
bubbleUp(idx) {
const element =
this
.heap[idx];
while
(idx > 0) {
const parentIdx = Math.floor((idx - 1) / 2);
const parent =
this
.heap[parentIdx];
if
(element >= parent) {
break
;
}
this
.heap[parentIdx] = element;
this
.heap[idx] = parent;
idx = parentIdx;
}
}
bubbleDown(idx) {
const element =
this
.heap[idx];
const length =
this
.heap.length;
while
(
true
) {
const leftChildIdx = idx * 2 + 1;
const rightChildIdx = idx * 2 + 2;
let leftChild, rightChild;
let swap =
null
;
if
(leftChildIdx < length) {
leftChild =
this
.heap[leftChildIdx];
if
(leftChild < element) {
swap = leftChildIdx;
}
}
if
(rightChildIdx < length) {
rightChild =
this
.heap[rightChildIdx];
if
(
(swap ===
null
&& rightChild < element) ||
(swap !==
null
&& rightChild < leftChild)
) {
swap = rightChildIdx;
}
}
if
(swap ===
null
) {
break
;
}
this
.heap[idx] =
this
.heap[swap];
this
.heap[swap] = element;
idx = swap;
}
}
size() {
return
this
.heap.length;
}
}
let arr = [100, 50, 50, 25];
let R = 2;
let N = arr.length;
console.log(countElements(R, N, arr));