-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3115_MaximumPrimeDifference.cpp
45 lines (39 loc) · 1.11 KB
/
3115_MaximumPrimeDifference.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Problem 3115: Maximum Prime Difference
// https://leetcode.com/problems/maximum-prime-difference/
#include <vector>
using namespace std;
class Solution {
public:
bool isPrime(int num) {
if (num == 1) {
return false;
}
int divisor = 2;
while (divisor * divisor <= num) {
if (num % divisor == 0) {
return false;
}
divisor += 1;
}
return true;
}
int maximumPrimeDifference(vector<int>& nums) {
// 跑迴圈找左邊的質數
int leftIndex = 0;
for (int i = 0; i < nums.size(); i++) {
if (isPrime(nums[i])) {
leftIndex = i;
break;
}
}
// 跑迴圈從後面往回找右邊的質數, 最多找到 leftIndex 後面一個, 沒找到就使用 leftIndex
int rightIndex = leftIndex;
for (int i = nums.size() - 1; i > leftIndex; i--) {
if (isPrime(nums[i])) {
rightIndex = i;
break;
}
}
return rightIndex - leftIndex;
}
};