Skip to content

Commit f6e5909

Browse files
Sync LeetCode submission Runtime - 107 ms (12.95%), Memory - 111.8 MB (7.57%)
1 parent 34c324f commit f6e5909

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<p>You are given an integer array <code>nums</code>.</p>
2+
3+
<p>Return an integer that is the <strong>maximum</strong> distance between the <strong>indices</strong> of two (not necessarily different) prime numbers in <code>nums</code><em>.</em></p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<div class="example-block">
9+
<p><strong>Input:</strong> <span class="example-io">nums = [4,2,9,5,3]</span></p>
10+
11+
<p><strong>Output:</strong> <span class="example-io">3</span></p>
12+
13+
<p><strong>Explanation:</strong> <code>nums[1]</code>, <code>nums[3]</code>, and <code>nums[4]</code> are prime. So the answer is <code>|4 - 1| = 3</code>.</p>
14+
</div>
15+
16+
<p><strong class="example">Example 2:</strong></p>
17+
18+
<div class="example-block">
19+
<p><strong>Input:</strong> <span class="example-io">nums = [4,8,2,8]</span></p>
20+
21+
<p><strong>Output:</strong> <span class="example-io">0</span></p>
22+
23+
<p><strong>Explanation:</strong> <code>nums[2]</code> is prime. Because there is just one prime number, the answer is <code>|2 - 2| = 0</code>.</p>
24+
</div>
25+
26+
<p>&nbsp;</p>
27+
<p><strong>Constraints:</strong></p>
28+
29+
<ul>
30+
<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>5</sup></code></li>
31+
<li><code>1 &lt;= nums[i] &lt;= 100</code></li>
32+
<li>The input is generated such that the number of prime numbers in the <code>nums</code> is at least one.</li>
33+
</ul>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
bool isPrime(int n) {
3+
if (n == 1) return false;
4+
for (int i=2; i*i<=n; i++) {
5+
if (n % i == 0) return false;
6+
}
7+
return true;
8+
}
9+
public:
10+
int maximumPrimeDifference(vector<int>& nums) {
11+
int n = nums.size();
12+
vector<int> primes;
13+
for (int i=0; i<n; i++) {
14+
if (isPrime(nums[i])) primes.push_back(i);
15+
}
16+
return primes[primes.size()-1] - primes[0];
17+
}
18+
};

0 commit comments

Comments
 (0)