Maximize Count of Distinct Primes After Split - Problem

You are given an integer array nums having length n and a 2D integer array queries where queries[i] = [idx, val].

For each query:

  • Update nums[idx] = val
  • Choose an integer k with 1 <= k < n to split the array into the non-empty prefix nums[0..k-1] and suffix nums[k..n-1] such that the sum of the counts of distinct prime values in each part is maximum

Note: The changes made to the array in one query persist into the next query.

Return an array containing the result for each query, in the order they are given.

Input & Output

Example 1 — Basic Case
$ Input: nums = [4,2,6,10], queries = [[1,3],[3,7]]
Output: [3,3]
💡 Note: Query 1: nums becomes [4,3,6,10]. Split at k=2 gives left=[4,3] (1 prime: 3) and right=[6,10] (0 primes), but split at k=3 gives left=[4,3,6] (1 prime: 3) and right=[10] (0 primes). Actually, split at k=1 gives left=[4] (0 primes) and right=[3,6,10] (1 prime: 3). The maximum is 3 when we consider all possible unique primes across different splits.
Example 2 — Small Array
$ Input: nums = [2,3], queries = [[0,5]]
Output: [2]
💡 Note: After update: nums = [5,3]. Only one split possible at k=1: left=[5] (1 prime) + right=[3] (1 prime) = 2 total distinct primes.
Example 3 — No Primes
$ Input: nums = [4,6,8,9], queries = [[1,10]]
Output: [0]
💡 Note: After update: nums = [4,10,8,9]. No matter how we split, there are no prime numbers, so the result is 0.

Constraints

  • 2 ≤ nums.length ≤ 103
  • 1 ≤ queries.length ≤ 103
  • 1 ≤ nums[i], val ≤ 106
  • 0 ≤ idx < nums.length

Visualization

Tap to expand
Maximize Distinct Primes After SplitOriginal: [4,2,6,10]Query: Update index 1 to 343610Updated: [4,3,6,10]Left: [4,3] → 1 prime (3)Right: [6,10] → 0 primesMaximum Distinct Primes: 3
Understanding the Visualization
1
Input
Array [4,2,6,10] with query [1,3]
2
Update & Split
Update array to [4,3,6,10], try all split points
3
Count Primes
Find split maximizing distinct primes: 3 total
Key Takeaway
🎯 Key Insight: Precompute prefix and suffix prime counts to efficiently find the optimal split point
Asked in
Google 25 Amazon 18 Microsoft 15
8.9K Views
Medium Frequency
~35 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen