Maximize Subarrays After Removing One Conflicting Pair Problem
Description
LeetCode Problem 3480.
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.
Example 1:
Input: n = 4, conflictingPairs = [[2,3],[1,4]]
Output: 9
Explanation:
- Remove [2, 3] from conflictingPairs. Now, conflictingPairs = [[1, 4]].
- There are 9 subarrays in nums where [1, 4] do not appear together. They are [1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [1, 2, 3] and [2, 3, 4].
- The maximum number of subarrays we can achieve after removing one element from conflictingPairs is 9.
Example 2:
Input: n = 5, conflictingPairs = [[1,2],[2,5],[3,5]]
Output: 12
Explanation:
- Remove [1, 2] from conflictingPairs. Now, conflictingPairs = [[2, 5], [3, 5]].
- There are 12 subarrays in nums where [2, 5] and [3, 5] do not appear together.
- The maximum number of subarrays we can achieve after removing one element from conflictingPairs is 12.
Constraints:
2 <= n <= 10^51 <= conflictingPairs.length <= 2 * nconflictingPairs[i].length == 21 <= conflictingPairs[i][j] <= nconflictingPairs[i][0] != conflictingPairs[i][1]
Solution
Approach: Sweep Left Endpoints with the Two Smallest Right Bounds
Normalize every pair so that a < b, and group the b values by their a.
For a fixed left endpoint l, a subarray [l, r] is valid as long as r stays below the smallest b among all pairs whose a >= l. Call that smallest value b1; it contributes b1 - l valid subarrays. Sweep l from n down to 1, keeping the smallest value b1 and the second smallest b2 seen so far.
Removing the pair that owns b1 raises the bound from b1 to b2, which gives b2 - b1 extra subarrays for this l. Collect these gains per b1 in an array gain[b1], because removing one pair helps every l that it limits.
The answer is the sum of all b1 - l plus the best single gain, max(gain).
Complexity: O(n + m) time and O(n + m) extra space, where m is the number of pairs.
class Solution:
def maxSubarrays(self, n: int, conflictingPairs: List[List[int]]) -> int:
g = [[] for _ in range(n + 1)]
for a, b in conflictingPairs:
if a > b:
a, b = b, a
g[a].append(b)
cnt = [0] * (n + 2)
ans = add = 0
b1 = b2 = n + 1
for a in range(n, 0, -1):
for b in g[a]:
if b < b1:
b2, b1 = b1, b
elif b < b2:
b2 = b
ans += b1 - a
cnt[b1] += b2 - b1
add = max(add, cnt[b1])
ans += add
return ans