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
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
Output: Maximum number of intersections possible with one horizontal line
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-coordinatesOutput: 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
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
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space for counters and variables
โ 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code