Skip to main content
Back to problems
Leetcode
Medium
Arrays
Number Theory
Maximum Prime Difference

Find the maximum distance between the first and last prime values in an array.

Acceptance 50%
Problem Statement

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 nums of length n.
  • 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

  • 1n1051 \le n \le 10^5
  • Values may be positive, zero, or negative.
  • Prime checks should treat numbers 1\le 1 as non-prime.
Examples
Sample cases returned by the problem API.

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.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.