Find the maximum width of a fence segment that can be formed from a set of line segments or posts after aligning and combining compatible parts.
Given a collection of fence pieces represented by positions or intervals on a line, determine the widest continuous fence that can be formed by joining pieces that touch or overlap. The goal is to compute the maximum possible span of any valid merged fence section.
A valid fence section is continuous: if two pieces overlap or meet at an endpoint, they can be treated as part of the same fence. Your task is to identify the widest such section across all pieces.
Input Format
- An array of intervals or fence pieces, where each piece is described by two endpoints.
- Each endpoint is an integer position on a number line.
- Intervals may be unsorted and may overlap or touch.
Output Format
- Return a single integer: the maximum width among all continuous merged fence sections.
- If no valid section exists, return 0.
Constraints
- is reasonably large for interview settings.
- Each segment endpoint fits in a 32-bit signed integer.
- Intervals may be unsorted.
- Touching endpoints are considered connectable when forming a continuous fence.
Example 1
Input
[[1,3],[2,6],[8,10],[9,12]]
Output
4
Explanation
The intervals [1,3] and [2,6] merge into [1,6], which has width 5 if measured as end-start, or 4 if the problem defines width by covered unit count. The widest merged continuous fence section is formed by the last two intervals as [8,12].
Example 2
Input
[[5,7],[1,2],[3,4]]
Output
2
Explanation
No intervals overlap or touch, so the widest fence section is just the widest individual segment.
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.