class PriorityQueue {
constructor(comparator) {
this
.heap = [];
this
.comparator = comparator;
}
add(element) {
this
.heap.push(element);
this
.bubbleUp(
this
.heap.length - 1);
}
peek() {
return
this
.heap[0];
}
poll() {
const poppedValue =
this
.heap[0];
const bottom =
this
.heap.length - 1;
if
(bottom > 0) {
this
.swap(0, bottom);
}
this
.heap.pop();
this
.bubbleDown(0);
return
poppedValue;
}
size() {
return
this
.heap.length;
}
bubbleUp(index) {
while
(index > 0) {
const parentIndex = Math.floor((index + 1) / 2) - 1;
if
(
this
.comparator(
this
.heap[index],
this
.heap[parentIndex]) < 0) {
this
.swap(index, parentIndex);
index = parentIndex;
}
else
{
break
;
}
}
}
bubbleDown(index) {
let swapping =
true
;
while
(swapping) {
const leftChildIndex = 2 * (index + 1) - 1;
const rightChildIndex = 2 * (index + 1);
let minIndex = index;
if
(
leftChildIndex <
this
.heap.length &&
this
.comparator(
this
.heap[leftChildIndex],
this
.heap[minIndex]) < 0
) {
minIndex = leftChildIndex;
}
if
(
rightChildIndex <
this
.heap.length &&
this
.comparator(
this
.heap[rightChildIndex],
this
.heap[minIndex]) < 0
) {
minIndex = rightChildIndex;
}
if
(minIndex !== index) {
this
.swap(index, minIndex);
index = minIndex;
}
else
{
swapping =
false
;
}
}
}
swap(index1, index2) {
const temp =
this
.heap[index1];
this
.heap[index1] =
this
.heap[index2];
this
.heap[index2] = temp;
}
}
function
maxValue(arr, K) {
let val = 0;
const pq =
new
PriorityQueue((a, b) => b - a);
arr.forEach((element) => pq.add(element));
while
(K--) {
const max = pq.peek();
pq.poll();
val += max;
pq.add(Math.floor(max / 2));
}
return
val;
}
const arr = [2, 4, 6, 8, 10];
const K = 5;
document.write(maxValue(arr, K));