SDE & MLE Prep

149. Max Points on a Line

Problem

Given distinct points on a plane, return the largest number of them that lie on one straight line.

Example: [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] → 4

Constraints: up to 300 points.

For each anchor point, group all other points by reduced slope (dy/g, dx/g) with a normalized sign. The largest group + 1 (the anchor) is the best line through that anchor.

Complexity: O(n²).

class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        best = 1
        for i, (x1, y1) in enumerate(points):
            slopes = defaultdict(int)
            for x2, y2 in points[i + 1:]:
                dx, dy = x2 - x1, y2 - y1
                g = math.gcd(dx, dy)
                dx, dy = dx // g, dy // g
                if dx < 0 or (dx == 0 and dy < 0):
                    dx, dy = -dx, -dy
                slopes[(dx, dy)] += 1
                best = max(best, slopes[(dx, dy)] + 1)
        return best