Maximum Number of Intersections on the Chart - Problem
Maximum Number of Intersections on the Chart

Imagine you have a line chart plotting stock prices over time. The chart consists of n points connected by line segments, where the k-th point has coordinates (k, y[k]). No two consecutive points share the same y-coordinate (no horizontal segments).

Your task is to find the maximum number of intersection points that can be achieved by drawing a single infinitely long horizontal line across this chart.

๐ŸŽฏ Goal: Return the maximum number of times a horizontal line can intersect with the line segments of the chart.

Input: A 1-indexed integer array y representing y-coordinates
Output: Maximum number of intersections possible with one horizontal line

Input & Output

example_1.py โ€” Basic Case
$ Input: [1, 3, 2, 4]
โ€บ Output: 2
๐Ÿ’ก Note: The chart has segments (1,1)โ†’(2,3), (2,3)โ†’(3,2), (3,2)โ†’(4,4). A horizontal line at height 2.5 intersects the first and third segments, giving maximum 2 intersections.
example_2.py โ€” All Increasing
$ Input: [1, 2, 3, 4, 5]
โ€บ Output: 0
๐Ÿ’ก Note: All segments are increasing, so no horizontal line can intersect any segment (intersections require line to pass between endpoints, not at endpoints).
example_3.py โ€” Zigzag Pattern
$ Input: [2, 1, 3, 1, 2]
โ€บ Output: 3
๐Ÿ’ก Note: With segments going up and down, a horizontal line at height 1.5 can intersect multiple segments simultaneously.

Visualization

Tap to expand
Maximum Intersections: 4h=235Time โ†’Price โ†‘
Understanding the Visualization
1
Plot the Chart
Connect consecutive points with line segments
2
Identify Critical Heights
Find y-values between consecutive points where intersections change
3
Count Intersections
For each critical height, count how many segments it crosses
4
Find Maximum
Return the height with the most intersections
Key Takeaway
๐ŸŽฏ Key Insight: Intersections only occur at specific y-values between consecutive points - we don't need to check every possible height!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(R ร— n)

Where R is the range of y-values (max - min), and n is array length. For each of R positions, we check n-1 segments

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space for counters and variables

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค y.length โ‰ค 105
  • 1 โ‰ค y[i] โ‰ค 109
  • No two consecutive points have the same y-coordinate
  • Array is 1-indexed in the problem description but 0-indexed in implementation
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
26.8K Views
Medium Frequency
~35 min Avg. Time
856 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