149. Max Points on a Line
Explanation
To solve this problem, we can iterate through each pair of points and calculate the slope of the line passing through them. By keeping track of the frequency of each slope in a hashmap, we can find the maximum number of points that lie on the same straight line.
- For each point, consider it as the starting point.
- Calculate the slope with all other points.
- Keep track of the frequency of each slope.
- Update the maximum number of points that lie on the same line for each starting point.
- Return the overall maximum.
Time complexity: O(n^2) where n is the number of points. Space complexity: O(n)
import java.util.*;
class Solution {
public int maxPoints(int[][] points) {
if (points.length <= 2) {
return points.length;
}
int maxPoints = 2; // At least 2 points are needed to form a line
for (int i = 0; i < points.length; i++) {
Map<Double, Integer> slopeMap = new HashMap<>();
int samePoints = 0;
int localMaxPoints = 1;
for (int j = 0; j < points.length; j++) {
if (i == j) continue;
int x1 = points[i][0];
int y1 = points[i][1];
int x2 = points[j][0];
int y2 = points[j][1];
if (x1 == x2 && y1 == y2) {
samePoints++;
} else {
double slope = (x1 == x2) ? Double.MAX_VALUE : 1.0 * (y2 - y1) / (x2 - x1);
slopeMap.put(slope, slopeMap.getOrDefault(slope, 1) + 1);
localMaxPoints = Math.max(localMaxPoints, slopeMap.get(slope));
}
}
maxPoints = Math.max(maxPoints, localMaxPoints + samePoints);
}
return maxPoints;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.