Max Points on a Line
Max Points on a Line
MathHash Table
Problem Statement
Given an array of points
where points[i] = [xi, yi]
represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.
Example
Example 1:
Input: points = [[1,1],[2,2],[3,3]]
Given points: [[1,1],[2,2],[3,3]]
Max points on a line: 3
Output: 3
Solution (Using Slopes)
A common approach to this problem is to iterate through each point and, for each point, calculate the slopes with all other points. We can use a hash map to store the counts of each slope. The maximum number of points on a line for a given starting point will be the maximum count in the hash map plus any duplicate points.
Algorithm Steps
- Iterate through each point
i
as a potential starting point of a line. - For each starting point
i
, create a hash map to store slopes with other points. - Iterate through the rest of the points
j
. - Calculate the slope between point
i
and pointj
. Handle vertical lines and duplicate points. - Store the slope and its count in the hash map.
- The maximum number of points for the line starting at
i
is the max count in the map plus any duplicates. - Keep track of the global maximum as you iterate through all starting points.
Slopes from point -1: {}
Max Points: 0
Start.
Max Points on a Line Solution