All problems
1129HardArraySegment TreeEnumerationPrefix Sum

Striking Out One Clash to Free the Most Stretches

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3480Maximize Subarrays After Removing One Conflicting Pair

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

Bins stand in a row numbered 1 through n. Each entry of clashes names two different bins that must never both lie inside a chosen stretch, where a stretch is any run of neighbouring bins.

Exactly one entry of clashes must be struck out. After that, count the non-empty stretches that hold no surviving entry's two bins together.

Return the largest count that striking out a single entry can leave.

Examples

Example 1

Input
n = 3, clashes = [[1, 2], [2, 3]]
Output
4

Whichever entry goes, one clash survives and rules out two of the six stretches, so four are left either way.

Example 2

Input
n = 2, clashes = [[1, 2]]
Output
3

Striking out the only entry leaves no clash at all, so all three stretches of the two bins count.

Example 3

Input
n = 2, clashes = [[1, 2], [1, 2]]
Output
2

Both entries name the same two bins, so striking one still leaves the other, and the single stretch covering both bins is ruled out.

Constraints

  • 2 <= n <= 10^5
  • 1 <= clashes.length <= 2 * n
  • clashes[i].length == 2
  • 1 <= clashes[i][0] <= n
  • 1 <= clashes[i][1] <= n
  • clashes[i][0] != clashes[i][1]

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def max_subarrays(n: int, clashes: list[list[int]]) -> int:
Java
public long maxSubarrays(int n, int[][] clashes)
September 7
Apply