Maximum Number of Intersections on the Chart - Problem

There is a line chart consisting of n points connected by line segments. You are given a 1-indexed integer array y. The kth 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.

Input & Output

Example 1 — Basic Case
$ Input: y = [1,4,2]
Output: 2
💡 Note: Chart has points (1,1), (2,4), (3,2). Line segments: (1,1)→(2,4) and (2,4)→(3,2). A horizontal line at y=2.5 intersects both segments, giving maximum 2 intersections.
Example 2 — Single Peak
$ Input: y = [2,1,3]
Output: 2
💡 Note: Points (1,2), (2,1), (3,3). Segments: (1,2)→(2,1) and (2,1)→(3,3). Horizontal line at y=1.5 intersects both segments.
Example 3 — Monotonic
$ Input: y = [1,2,3,4]
Output: 3
💡 Note: Points form ascending line. Any horizontal line between y=1.5 and y=3.5 intersects all 3 segments: (1,1)→(2,2), (2,2)→(3,3), (3,3)→(4,4).

Constraints

  • 2 ≤ y.length ≤ 105
  • 1 ≤ y[i] ≤ 108
  • No two consecutive elements are equal

Visualization

Tap to expand
Maximum Intersections on Chart INPUT 4 3 2 1 1 2 3 y=2.5 Input Array: y 1 y[1] 4 y[2] 2 y[3] n = 3 points ALGORITHM STEPS 1 Coordinate Compress Map y-values to events 2 Create Events For each segment: start/end 3 Sweep Line Process events by y-coord 4 Track Maximum Count active segments Sweep Line Events Y Event Active 1 +1 (start) 1 2 +1 (start) 2 4 -1 (end) 1 MAX Max active segments = 2 FINAL RESULT 2 intersections Output 2 Maximum intersections with any horizontal line Key Insight: Each line segment between consecutive points is treated as an interval [min(y[k], y[k+1]), max(y[k], y[k+1])]. A horizontal line at height h intersects a segment if h lies within its y-range. Using sweep line, we count overlapping intervals at each y-coordinate to find the maximum number of intersections. TutorialsPoint - Maximum Number of Intersections on the Chart | Coordinate Compression + Sweep Line
Asked in
Google 15 Microsoft 12
8.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen