Max Points on a Line
ID:149
Input: points = [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
Output: 4Idea
Code
public int maxPoints(int[][] points) {
if (points.length <= 2) return points.length;
int result = 0;
for (int i = 0;i<points.length;i++){
Map<Double, Integer> map = new HashMap<>();
int count = 1;
int same = 0;
for (int j = 0;j<points.length;j++){
if(j != i){
int firstX = points[i][0];
int firstY = points[i][1];
int secondX = points[j][0];
int secondY = points[j][1];
// vertical line
if (firstX == secondX) {
count++;
continue;
}
double k = (double)(secondY - firstY) / (double)(secondX - firstX);
map.put(k, map.getOrDefault(k, 1)+1);
result = Math.max(result, map.get(k));
}
}
result = Math.max(result, count);
}
return result;
}Last updated
