class MaxHeap {
constructor() {
this
.values = [];
}
parent(index) {
return
Math.floor((index - 1) / 2);
}
leftChild(index) {
return
(index * 2) + 1;
}
rightChild(index) {
return
(index * 2) + 2;
}
isLeaf(index) {
return
(
index >= Math.floor(
this
.values.length / 2) && index <=
this
.values.length - 1
)
}
swap(index1, index2) {
[
this
.values[index1],
this
.values[index2]] = [
this
.values[index2],
this
.values[index1]];
}
heapifyDown(index) {
if
(!
this
.isLeaf(index)) {
let leftChildIndex =
this
.leftChild(index),
rightChildIndex =
this
.rightChild(index),
largestIndex = index;
if
(
this
.values[leftChildIndex] >
this
.values[largestIndex]) {
largestIndex = leftChildIndex;
}
if
(
this
.values[rightChildIndex] >=
this
.values[largestIndex]) {
largestIndex = rightChildIndex;
}
if
(largestIndex !== index) {
this
.swap(index, largestIndex);
this
.heapifyDown(largestIndex);
}
}
}
heapifyUp(index) {
let currentIndex = index,
parentIndex =
this
.parent(currentIndex);
while
(currentIndex > 0 &&
this
.values[currentIndex] >
this
.values[parentIndex]) {
this
.swap(currentIndex, parentIndex);
currentIndex = parentIndex;
parentIndex =
this
.parent(parentIndex);
}
}
add(element) {
this
.values.push(element);
this
.heapifyUp(
this
.values.length - 1);
}
peek() {
return
this
.values[0];
}
extractMax() {
if
(
this
.values.length < 1)
return
'heap is empty'
;
const max =
this
.values[0];
const end =
this
.values.pop();
this
.values[0] = end;
this
.heapifyDown(0);
return
max;
}
buildHeap(array) {
this
.values = array;
for
(let i = Math.floor(
this
.values.length / 2); i >= 0; i--){
this
.heapifyDown(i);
}
}
}
function
findmax_profit(profit, str, n)
{
let pq =
new
MaxHeap();
let res = 0;
for
(let i = 0; i < n; i++) {
pq.add(profit[i]);
if
(str[i] ==
'1'
) {
res += pq.peek();
pq.extractMax();
}
}
return
res;
}
let profit = [ 12, 10, 5, 8, 9, 6 ];
let str =
"001110"
;
let N = profit.length;
console.log(findmax_profit(profit, str, N));
let profit1 = [ 10, 5, 8, 9, 6 ];
let str1 =
"01110"
;
N = profit.length;
console.log(findmax_profit(profit1, str1, N));
let profit2 = [ 20, 10, 9, 30, 20, 9 ];
let str2 =
"011011"
;
N = profit.length;
console.log(findmax_profit(profit2, str2, N));