![]() |
VOOZH | about |
Given a line chart with n points connected by line segments and a 1-indexed integer array y[], where the ith point has coordinates (i, y[i]). There are no horizontal lines, meaning no two consecutive points have the same y-coordinate. The task is to find the maximum number of points of intersection of an infinitely long horizontal line with the chart.
Example:
Input: y = [1,2,1,2,1,3,2]
Output: 5
Explanation: As you can see in the image above, the line y = 1.5 has 5 intersections with the chart (in red crosses). You can also see the line y = 2 which intersects the chart in 4 points (in red crosses). It can be shown that there is no horizontal line intersecting the chart at more than 5 points. So the answer would be 5.Input: y = [2,1,3,4,5]
Output: 2
Explanation: As you can see in the image above, the line y = 1.5 has 2 intersections with the chart (in red crosses). You can also see the line y = 2 which intersects the chart in 2 points (in red crosses). It can be shown that there is no horizontal line intersecting the chart at more than 2 points. So the answer would be 2.
Approach:
Create and ordered map of + and - with the coordinates. Then we can sweep through the map from least to greatest while keeping a running sum which is equal to the number of intersections of a horizontal line at the current y coordinate.
Trick is to multiply each number by 2 to create space after each number; we need this if we want to avoid using floating points, because for example, if we have test case {2,1,3}, we need to have a -1 between 2 and 3.
Steps to solve this problem:
Below is the Implementation of above approach:
5
Time complexity: O(nlog(n))
Space complexity: O(n)