const NUM = 10e4 + 1;
const factors = Array.from({ length: NUM }, () => []);
function
getFactors() {
for
(let i = 2; i < NUM; i++) {
for
(let j = i; j < NUM; j += i) {
factors[j].push(i);
}
}
}
function
findMinimumRange(N, A) {
getFactors();
const s =
new
Set(A);
const uniSorted = Array.from(s).sort((a, b) => a - b);
N = uniSorted.length;
const pq =
new
PriorityQueue((a, b) => a[0] - b[0]);
let maximum = 0;
const startIndexes =
new
Array(N + 1).fill(0);
for
(let i = 0; i < N; i++) {
pq.enqueue([factors[uniSorted[i]][0], i]);
maximum = Math.max(maximum, factors[uniSorted[i]][0]);
}
let ans = maximum - pq.peek()[0];
while
(!pq.isEmpty()) {
const [ind, index] = pq.dequeue();
if
(startIndexes[index] + 1 === factors[uniSorted[index]].length) {
break
;
}
startIndexes[index] += 1;
pq.enqueue([factors[uniSorted[index]][startIndexes[index]], index]);
maximum = Math.max(maximum, factors[uniSorted[index]][startIndexes[index]]);
ans = Math.min(ans, maximum - pq.peek()[0]);
}
return
ans;
}
class PriorityQueue {
constructor(compare) {
this
.heap = [];
this
.compare = compare;
}
enqueue(value) {
this
.heap.push(value);
this
.bubbleUp();
}
dequeue() {
const root =
this
.heap[0];
const last =
this
.heap.pop();
if
(
this
.heap.length > 0) {
this
.heap[0] = last;
this
.bubbleDown();
}
return
root;
}
peek() {
return
this
.heap[0];
}
isEmpty() {
return
this
.heap.length === 0;
}
bubbleUp() {
let index =
this
.heap.length - 1;
while
(index > 0) {
const parentIndex = Math.floor((index - 1) / 2);
if
(
this
.compare(
this
.heap[index],
this
.heap[parentIndex]) < 0) {
this
.swap(index, parentIndex);
index = parentIndex;
}
else
{
break
;
}
}
}
bubbleDown() {
let index = 0;
while
(
true
) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let smallestChildIndex = index;
if
(leftChildIndex <
this
.heap.length &&
this
.compare(
this
.heap[leftChildIndex],
this
.heap[smallestChildIndex]) < 0) {
smallestChildIndex = leftChildIndex;
}
if
(rightChildIndex <
this
.heap.length &&
this
.compare(
this
.heap[rightChildIndex],
this
.heap[smallestChildIndex]) < 0) {
smallestChildIndex = rightChildIndex;
}
if
(smallestChildIndex !== index) {
this
.swap(index, smallestChildIndex);
index = smallestChildIndex;
}
else
{
break
;
}
}
}
swap(i, j) {
[
this
.heap[i],
this
.heap[j]] = [
this
.heap[j],
this
.heap[i]];
}
}
const N = 3;
const A = [3, 9, 8];
console.log(findMinimumRange(N, A));