Maximum Number of Intersections on the Chart Problem
Description
LeetCode Problem 3009.
There is a line chart consisting of n points connected by line segments. You are given a 1-indexed integer array y. The k^th point has coordinates (k, y[k]). There are no horizontal lines; that is, no two consecutive points have the same y-coordinate.
We can draw an infinitely long horizontal line. Return the maximum number of points of intersection of the line with the chart.
Example 1:

Input: y = [1,2,1,2,1,3,2]
Output: 5
Explanation: As you can see in the image above, the line y = 1.5 has 5 intersections with the chart (in red crosses). You can also see the line y = 2 which intersects the chart in 4 points (in red crosses). It can be shown that there is no horizontal line intersecting the chart at more than 5 points. So the answer would be 5.
Example 2:

Input: y = [2,1,3,4,5]
Output: 2
Explanation: As you can see in the image above, the line y = 1.5 has 2 intersections with the chart (in red crosses). You can also see the line y = 2 which intersects the chart in 2 points (in red crosses). It can be shown that there is no horizontal line intersecting the chart at more than 2 points. So the answer would be 2.
Constraints:
2 <= y.length <= 10^51 <= y[i] <= 10^9y[i] != y[i + 1]foriin range[1, n - 1]
Solution
Approach: Sweep Line over Doubled Coordinates
A horizontal line crosses the chart at the most points either at some y = v or just between two integers, so we can restrict the search to doubled coordinates and treat each chart segment as an interval of y values.
Double all heights so that y + 0.5 becomes an integer. A segment from y[i-1] to y[i] covers the interval between those doubled values. To avoid counting a shared vertex twice, shrink the interval by one at the end where the chart continues in the same direction (the last segment keeps its end). Then:
- Add
+1at the interval's low end and-1just after its high end in a sorted map. - Sweep the keys in order, keep a running sum, and take its maximum: that is the largest number of segments covered by one horizontal line.
Complexity: O(n log n) time (sorting the events) and O(n) space.
from collections import defaultdict
class Solution:
def maxIntersectionCount(self, y: List[int]) -> int:
n = len(y)
line = defaultdict(int)
for i in range(1, n):
start = 2 * y[i - 1]
end = 2 * y[i] + (0 if i == n - 1 else (-1 if y[i] > y[i - 1] else 1))
line[min(start, end)] += 1
line[max(start, end) + 1] -= 1
ans = intersection = 0
for _, count in sorted(line.items()):
intersection += count
ans = max(ans, intersection)
return ans