LeetCode 3115: Maximum Prime Difference Solution
Master LeetCode problem 3115 (Maximum Prime Difference), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
3115. Maximum Prime Difference
Problem Explanation
Explanation
To solve this problem, we need to find the maximum distance between the indices of two prime numbers in the given array nums. We can achieve this by iterating through the array, checking if each number is prime, and keeping track of the indices of the prime numbers we encounter. Finally, we calculate the maximum distance between any two prime number indices.
Here is the algorithmic idea:
- Iterate through the array
nums. - For each number, check if it is prime.
- If a number is prime, update the index of the previous prime number encountered and calculate the current distance.
- Update the maximum distance found so far.
- Return the maximum distance.
Time complexity: O(n * sqrt(max(nums))), where n is the number of elements in the array and sqrt(max(nums)) is the complexity of checking if a number is prime. Space complexity: O(1) - constant space used.
Solution Code
class Solution {
public int maxPrimeDifference(int[] nums) {
int maxDiff = 0;
int prevPrimeIndex = -1;
for (int i = 0; i < nums.length; i++) {
if (isPrime(nums[i])) {
if (prevPrimeIndex != -1) {
maxDiff = Math.max(maxDiff, i - prevPrimeIndex);
}
prevPrimeIndex = i;
}
}
return maxDiff;
}
private boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) return false;
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 3115 (Maximum Prime Difference)?
This page provides optimized solutions for LeetCode problem 3115 (Maximum Prime Difference) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 3115 (Maximum Prime Difference)?
The time complexity for LeetCode 3115 (Maximum Prime Difference) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 3115 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3115 in Java, C++, or Python.