Problem Description
Given an array y representing the y‐coordinates of n points (with x‑coordinates 1, 2, …, n) that are connected sequentially by line segments (with no horizontal segments), an infinitely long horizontal line is drawn. The task is to choose a y = c such that the line “cuts” the chart at as many points as possible. In other words, for each segment connecting (i, y[i]) and (i+1, y[i+1]), if c lies strictly between y[i] and y[i+1], then it counts as an intersection. Return the maximum intersection count that can be attained by any horizontal line.
Key Insights
- The chart is formed by connecting consecutive points; each segment is strictly monotonic (since no two consecutive points share the same y‐value).
- Every segment creates an open interval (min(y[i], y[i+1]), max(y[i], y[i+1])). A horizontal line at c will intersect the segment if and only if c lies strictly in that interval.
- The problem reduces to choosing a c that lies in as many of these open intervals as possible.
- This is analogous to the “maximum overlapping intervals” problem. We can use a sweep line algorithm.
- By processing “start” events (the lower y of the segment) and “end” events (the higher y of the segment) carefully (remembering that endpoints are not included), we can find the maximum count of intervals overlapping any gap between distinct endpoints.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting of 2*(n-1) events. Space Complexity: O(n) for storing the events.
Solution
We first convert each segment connecting consecutive points into an interval (a, b) where a = min(y[i], y[i+1]) and b = max(y[i], y[i+1]). A horizontal line crosses the segment if its y = c satisfies a < c < b.
We then create two kinds of events:
- A “start” event at a indicating that for any candidate c > a, this segment will count.
- An “end” event at b indicating that for any candidate c ≥ b, this segment no longer counts.
We sort these events by coordinate. When processing events at the same coordinate, we subtract (process end events) before adding (process start events) because endpoints are not included in the open interval. As we sweep through the events, the maximum active count (active intervals that cover a gap between two event coordinates) corresponds to the maximum intersections with the chart.