Find the maximum distance between the first and last prime values in an array.
Given an integer array, identify all prime numbers present in the array and compute the difference between the index of the last prime and the index of the first prime. Return the largest such difference, which is simply the span from the earliest prime occurrence to the latest prime occurrence.
A prime number is an integer greater than 1 that has exactly two positive divisors: 1 and itself.
Input Format
- An integer array
numsof lengthn. - Each
nums[i]is an integer.
Return the maximum prime difference based on the positions of prime elements in the array.
Output Format
- Return a single integer:
lastPrimeIndex - firstPrimeIndex. - If there are fewer than two prime numbers, return
0.
Constraints
- Values may be positive, zero, or negative.
- Prime checks should treat numbers as non-prime.
Example 1
Input
nums = [4, 2, 9, 5, 8, 3]
Output
4
Explanation
The prime numbers appear at indices 1, 3, and 5. The span from the first prime to the last prime is 5 - 1 = 4.
Example 2
Input
nums = [1, 4, 6, 8]
Output
0
Explanation
There are no prime numbers, so the maximum prime difference is 0.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.