Ctrl K

A Level Line Through the Chart

Hard
A line chart is drawn on the plane: its k-th vertex (counting from one) sits at (k, heights[k - 1]), and neighbouring vertices are joined by segments. No two neighbouring vertices share a height, so there are no horizontal segments. Draw an infinite horizontal line at any height (not necessarily an integer). Return the largest number of points where it can meet the chart. A vertex the line passes through counts as one point.
Example 1
heights=[2, 4, 1, 3, 2, 4] → 5

The line at height 2.5 crosses all five segments of the chart, and more than five points is impossible because the chart has only five segments.

Example 2
heights=[1, 5] → 1

The chart is a single segment, so any suitable line meets it at exactly one point.

Example 3
heights=[3, 1, 3, 1, 3] → 4
Constraints
  • 2 ≤ len(heights) ≤ 10⁵
  • 1 ≤ heights[i] ≤ 10⁹
  • heights[i] ≠ heights[i + 1]
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsClean Rectangle on Pins HardEmpty Rectangle From Marked Points MediumStars on One Straight Line HardDoes the Robot Cross Its Trail HardRope Around the Posts Hard
loading Python…
Input
heights=[2, 4, 1, 3, 2, 4]
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 173 tests on the server, hidden ones included.