Maximum Prime Difference Problem
#3115
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3115.
You are given an integer array nums.
Return an integer that is the maximum distance between the indices of two (not necessarily different) prime numbers in nums.
Example 1:
Input: nums = [4,2,9,5,3]
Output: 3
Explanation: nums[1], nums[3], and nums[4] are prime. So the answer is |4 - 1| = 3.
Example 2:
Input: nums = [4,8,2,8]
Output: 0
Explanation: nums[2] is prime. Because there is just one prime number, the answer is |2 - 2| = 0.
Constraints:
1 <= nums.length <= 3 * 10^51 <= nums[i] <= 100- The input is generated such that the number of prime numbers in the
numsis at least one.
Solution
Approach: Two scans
The best pair is the first prime and the last prime. Scan from the left to find the first prime index i, then from the right to find the last prime index j, and return j - i. Primality is checked by trial division up to the square root.
Complexity: O(n sqrt(M)) time and O(1) space, where M is the largest value in the array.
from math import sqrt
class Solution:
def maximumPrimeDifference(self, nums: List[int]) -> int:
def is_prime(x: int) -> bool:
if x < 2:
return False
return all(x % i for i in range(2, int(sqrt(x)) + 1))
for i, x in enumerate(nums):
if is_prime(x):
for j in range(len(nums) - 1, i - 1, -1):
if is_prime(nums[j]):
return j - i