function
maxPower(a, b, n, k) {
const pq =
new
PriorityQueue((a, b) => a[0] - b[0]);
for
(let i = 0; i < n; i++) {
pq.enqueue([a[i], b[i]]);
}
let curPower = k;
while
(!pq.isEmpty()) {
const [guardPower, extraPower] = pq.dequeue();
if
(guardPower > curPower) {
break
;
}
curPower += extraPower;
}
return
curPower;
}
class PriorityQueue {
constructor(compare) {
this
.heap = [];
this
.compare = compare;
}
enqueue(item) {
this
.heap.push(item);
this
._shiftUp();
}
dequeue() {
if
(
this
.isEmpty()) {
throw
new
Error(
"Priority queue is empty"
);
}
const first = 0;
const last =
this
.heap.length - 1;
this
._swap(first, last);
const item =
this
.heap.pop();
this
._shiftDown();
return
item;
}
isEmpty() {
return
this
.heap.length === 0;
}
_getParentIndex(childIndex) {
return
Math.floor((childIndex - 1) / 2);
}
_getLeftChildIndex(parentIndex) {
return
parentIndex * 2 + 1;
}
_getRightChildIndex(parentIndex) {
return
parentIndex * 2 + 2;
}
_hasParent(childIndex) {
return
this
._getParentIndex(childIndex) >= 0;
}
_hasLeftChild(parentIndex) {
return
this
._getLeftChildIndex(parentIndex) <
this
.heap.length;
}
_hasRightChild(parentIndex) {
return
this
._getRightChildIndex(parentIndex) <
this
.heap.length;
}
_getParent(childIndex) {
return
this
.heap[
this
._getParentIndex(childIndex)];
}
_getLeftChild(parentIndex) {
return
this
.heap[
this
._getLeftChildIndex(parentIndex)];
}
_getRightChild(parentIndex) {
return
this
.heap[
this
._getRightChildIndex(parentIndex)];
}
_swap(index1, index2) {
[
this
.heap[index1],
this
.heap[index2]] = [
this
.heap[index2],
this
.heap[index1],
];
}
_shiftUp() {
let index =
this
.heap.length - 1;
while
(
this
._hasParent(index) &&
this
.compare(
this
.heap[index],
this
._getParent(index)) < 0
) {
const parentIndex =
this
._getParentIndex(index);
this
._swap(index, parentIndex);
index = parentIndex;
}
}
_shiftDown() {
let index = 0;
while
(
this
._hasLeftChild(index)) {
let smallerChildIndex =
this
._getLeftChildIndex(index);
if
(
this
._hasRightChild(index) &&
this
.compare(
this
._getRightChild(index),
this
._getLeftChild(index)) < 0
) {
smallerChildIndex =
this
._getRightChildIndex(index);
}
if
(
this
.compare(
this
.heap[index],
this
.heap[smallerChildIndex]) < 0
) {
break
;
}
else
{
this
._swap(index, smallerChildIndex);
}
index = smallerChildIndex;
}
}
}
function
main() {
const a = [20, 30, 10];
const b = [9, 100, 10];
const n = a.length;
const k = 10;
const maxPoweR = maxPower(a, b, n, k);
console.log(maxPoweR);
}
main();