Skip to content

Commit 67b5d2e

Browse files
committedMar 7, 2025
Add solution #2523
1 parent c2f3a95 commit 67b5d2e

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,7 @@
745745
2482|[Difference Between Ones and Zeros in Row and Column](./2482-difference-between-ones-and-zeros-in-row-and-column.js)|Medium|
746746
2490|[Circular Sentence](./2490-circular-sentence.js)|Easy|
747747
2493|[Divide Nodes Into the Maximum Number of Groups](./2493-divide-nodes-into-the-maximum-number-of-groups.js)|Hard|
748+
2523|[Closest Prime Numbers in Range](./2523-closest-prime-numbers-in-range.js)|Medium|
748749
2529|[Maximum Count of Positive Integer and Negative Integer](./2529-maximum-count-of-positive-integer-and-negative-integer.js)|Easy|
749750
2535|[Difference Between Element Sum and Digit Sum of an Array](./2535-difference-between-element-sum-and-digit-sum-of-an-array.js)|Easy|
750751
2542|[Maximum Subsequence Score](./2542-maximum-subsequence-score.js)|Medium|
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/**
2+
* 2523. Closest Prime Numbers in Range
3+
* https://leetcode.com/problems/closest-prime-numbers-in-range/
4+
* Difficulty: Medium
5+
*
6+
* Given two positive integers left and right, find the two integers num1 and num2 such that:
7+
* - left <= num1 < num2 <= right
8+
* - Both num1 and num2 are prime numbers.
9+
* - num2 - num1 is the minimum amongst all other pairs satisfying the above conditions.
10+
*
11+
* Return the positive integer array ans = [num1, num2]. If there are multiple pairs satisfying
12+
* these conditions, return the one with the smallest num1 value. If no such numbers exist,
13+
* return [-1, -1].
14+
*/
15+
16+
/**
17+
* @param {number} left
18+
* @param {number} right
19+
* @return {number[]}
20+
*/
21+
var closestPrimes = function(left, right) {
22+
const group = new Uint8Array(right + 1).fill(1);
23+
let result = [-1, -1];
24+
25+
group[0] = group[1] = 0;
26+
for (let i = 2; i * i <= right; i++) {
27+
if (group[i]) {
28+
for (let j = i * i; j <= right; j += i) {
29+
group[j] = 0;
30+
}
31+
}
32+
}
33+
for (let i = Math.max(2, left), prev = -1, min = Infinity; i <= right; i++) {
34+
if (group[i]) {
35+
if (prev !== -1 && i - prev < min) {
36+
min = i - prev;
37+
result = [prev, i];
38+
}
39+
prev = i;
40+
}
41+
}
42+
43+
return result;
44+
};

0 commit comments

Comments
 (0)
Please sign in to comment.