AlgoMaster Logo

Max Points on a Line

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force Approach

Intuition:

This approach considers all combinations of pairs to determine every possible line. For each line, we check how many points from the input lie on it.

Steps:

  1. Iterate over each pair of points.
  2. For each pair, calculate the slope.
  3. Count how many points lie on the line defined by this slope.
  4. Keep track of the maximum count.

Code:

2. Optimized Approach Using HashMap

Intuition:

Instead of evaluating every pair by brute force, leverage the properties of the slope of lines and use a HashMap to optimize the counting of points on a similar slope from a given point.

Steps:

  1. Iterate over each point and treat it as the base point.
  2. Use a HashMap to store the slope of lines that include the base point.
  3. For each other point, calculate the simplified form of the slope and use it as the key in the HashMap.
  4. Determine the highest count of points that lie on any line based from the current base point.
  5. Keep track of the maximum count across all base points.

Code: