Maximize Subarrays After Removing One Conflicting Pair - Problem

You are given an integer n which represents an array nums containing the numbers from 1 to n in order. Additionally, you are given a 2D array conflictingPairs, where conflictingPairs[i] = [a, b] indicates that a and b form a conflicting pair.

Remove exactly one element from conflictingPairs. Afterward, count the number of non-empty subarrays of nums which do not contain both a and b for any remaining conflicting pair [a, b].

Return the maximum number of subarrays possible after removing exactly one conflicting pair.

Input & Output

Example 1 — Basic Case
$ Input: n = 5, conflictingPairs = [[1,5], [2,3]]
Output: 9
💡 Note: Remove [2,3] to get max subarrays. With only [1,5] remaining, we avoid subarrays containing both 1 and 5. Valid count: total 15 minus 1×1=1 invalid equals 14, but removing [1,5] gives 15-2×3=9.
Example 2 — Single Pair
$ Input: n = 4, conflictingPairs = [[2,4]]
Output: 10
💡 Note: Only one pair to remove [2,4]. Total subarrays = 4×5/2 = 10. After removal, no constraints remain, so all 10 subarrays are valid.
Example 3 — Multiple Pairs
$ Input: n = 3, conflictingPairs = [[1,2], [2,3]]
Output: 4
💡 Note: Remove [1,2] keeps [2,3]. Invalid subarrays contain both 2 and 3: positions 2×2=4, but total is only 6, so 6-2=4 valid. Remove [2,3] keeps [1,2]: 6-2=4 valid. Both give same result.

Constraints

  • 2 ≤ n ≤ 105
  • 1 ≤ conflictingPairs.length ≤ 105
  • conflictingPairs[i].length == 2
  • 1 ≤ conflictingPairs[i][0], conflictingPairs[i][1] ≤ n
  • conflictingPairs[i][0] ≠ conflictingPairs[i][1]

Visualization

Tap to expand
Maximize Subarrays: Remove One Conflicting Pair12345Array: [1,2,3,4,5]Conflicting: [1,5]Conflicting: [2,4]Remove [1,5]Valid subarrays: XRemove [2,4]Valid subarrays: YOutput: max(X, Y)Choose removal that maximizes valid subarray count
Understanding the Visualization
1
Input
Array [1,2,3,4,5] with conflicting pairs [[1,5],[2,4]]
2
Process
Try removing each pair and count valid subarrays
3
Output
Maximum valid subarray count after optimal pair removal
Key Takeaway
🎯 Key Insight: Each conflicting pair restricts different subarrays - remove the most restrictive one
Asked in
Google 25 Microsoft 15 Amazon 10
27.7K Views
Medium Frequency
~35 min Avg. Time
892 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