720. Maximum Number of Intersections on the Chart

You are given a chart that is formed by connecting a sequence of points with straight line segments. The chart consists of n points where the kth point is located at (k, y[k]). It is guaranteed that no two consecutive points share the same y‑coordinate (i.e. there are no horizontal segments).

You are allowed to draw an infinitely long horizontal line (of the form y = c, where c is any constant). Your goal is to choose the value of c so that the horizontal line intersects the chart at as many distinct points as possible. In other words, determine the maximum number of distinct intersection points between some horizontal line and the segments of the chart.

Return that maximum intersection count.

Example 1:

Input : y = [4, 7, 4, 7, 4, 8, 7]

Output : 5

Explanation :

Consider drawing the horizontal line at y = 5.5. It crosses the following segments:

  • Between (1, 4) and (2, 7)
  • Between (2, 7) and (3, 4)
  • Between (3, 4) and (4, 7)
  • Between (4, 7) and (5, 4)
  • Between (5, 4) and (6, 8)

The last segment from (6, 8) to (7, 7) is not intersected by y = 5.5. No horizontal line can produce more than 5 distinct intersections, so the answer is 5.

Example 2:

Input : y = [10, 3, 12, 15, 6]

Output : 3

Explanation :

One optimal choice is to draw the horizontal line at y = 8. With this line:

  • It intersects the segment from (1, 10) to (2, 3) (since 8 lies between 3 and 10).
  • It intersects the segment from (2, 3) to (3, 12) (8 is between 3 and 12).
  • It also intersects the segment from (4, 15) to (5, 6) (8 is between 6 and 15).

No other horizontal line can yield more than 3 intersections, so the answer is 3.

Now Your Turn!

Pick the correct output for the given input

Input : y = [7, 4, 8, 9, 10]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 2 <= y.length <= 105
  • 1 <= y[i] <= 109
  • y[i] != y[i + 1] for i in range [1, n - 1]

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int maxIntersectionCount(vector<int>& Y) {
// Your code goes here
}
};
 
Test Case

Input:

Y