3115. Maximum Prime Difference
class Solution {
public:
bool isPrime(const int& x) {
if (x < 2) return false;
if (x < 4) return true;
if (x % 2 == 0 || x % 3 == 0) return false;
const int range = sqrt(x) + 1;
for (int i = 5; i < range; ++i) {
if (x % i == 0 || x % (i + 2) == 0) return false;
}
return true;
}
int maximumPrimeDifference(vector<int>& nums) {
int front = 0;
// Find front
for(int i = 0; i < nums.size(); ++i) {
if (isPrime(nums[i])) {
front = i;
break;
}
}
int back = front;
// Find back
for (int i = nums.size() - 1; i > front; --i) {
if (isPrime(nums[i])) {
back = i;
break;
}
}
return back - front;
}
};
Last updated