function
minimumNumber(n, arr) {
if
(n === 1) {
return
arr[0];
}
let pq =
new
PriorityQueue();
for
(let num of arr) {
pq.enqueue(num);
}
while
(
true
) {
let a = pq.dequeue();
let b = pq.peek();
if
(b === 0) {
return
a;
}
a -= b;
pq.enqueue(a);
}
}
class PriorityQueue {
constructor() {
this
.heap = [];
}
enqueue(value) {
this
.heap.push(value);
this
.bubbleUp(
this
.heap.length - 1);
}
dequeue() {
if
(
this
.isEmpty()) {
return
null
;
}
this
.swap(0,
this
.heap.length - 1);
const value =
this
.heap.pop();
this
.bubbleDown(0);
return
value;
}
peek() {
if
(
this
.isEmpty()) {
return
null
;
}
return
this
.heap[0];
}
isEmpty() {
return
this
.heap.length === 0;
}
bubbleUp(index) {
const parentIndex = Math.floor((index - 1) / 2);
if
(parentIndex >= 0 &&
this
.heap[parentIndex] <
this
.heap[index]) {
this
.swap(parentIndex, index);
this
.bubbleUp(parentIndex);
}
}
bubbleDown(index) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let maxIndex = index;
if
(
leftChildIndex <
this
.heap.length &&
this
.heap[leftChildIndex] >
this
.heap[maxIndex]
) {
maxIndex = leftChildIndex;
}
if
(
rightChildIndex <
this
.heap.length &&
this
.heap[rightChildIndex] >
this
.heap[maxIndex]
) {
maxIndex = rightChildIndex;
}
if
(maxIndex !== index) {
this
.swap(maxIndex, index);
this
.bubbleDown(maxIndex);
}
}
swap(i, j) {
[
this
.heap[i],
this
.heap[j]] = [
this
.heap[j],
this
.heap[i]];
}
}
let n = 3;
let arr = [3, 2, 4];
document.write(minimumNumber(n, arr));
</script>