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: y = [1,4,2](1,1)(2,4)(3,2)y = 2.5Result✓ Segment 1→2 intersected✓ Segment 2→3 intersectedTotal: 2Maximum intersections: 2
Understanding the Visualization
1
Input Chart
Line chart with points connected by segments
2
Test Horizontal Lines
Find optimal y-coordinate for maximum intersections
3
Count Intersections
Return maximum number of segments intersected
Key Takeaway
🎯 Key Insight: Use sweep line algorithm to efficiently find the y-coordinate where the most line segments are active simultaneously
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