Max Points on a Line

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.

30:00

Max Points on a Line
hard
Free written solution
Topics
Companies

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 1:
Input: {"points":[[1,1],[2,2],[3,3]]}
Output: 3
Constraints:
  • 1≤points.length≤3001 \leq \text{points.length} \leq 300

  • points[i].length==2\text{points}[i].\text{length} == 2

  • −104≤xi,yi≤104-10^4 \leq x_i, y_i \leq 10^4

  • All the points are unique.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"points":[[1,1],[2,2],[3,3]]}

3 points. Two points always share a line, so the question is how many can share one. Plan: fix an anchor and group every later point by its direction from the anchor.

012
● anchor i● partner j— best line

slopes (anchors done: 0/3)

empty

best (points besides the anchor)

0

Variables
VariableValue
n3
best0
DepthFunction Call
Stack empty
0/12