_149 Max Points on a Line [Updated solution]
Anacoder1 opened this issue · 2 comments
Anacoder1 commented
Input types were changed on April 15, 2019.
The solution in _149.java doesn't work anymore.
Below is the new solution: (credits)
class Solution {
public int maxPoints(int[][] points) {
if(points.length < 3)return points.length;
int max = 0;
HashMap<Long, Integer> map = new HashMap<Long, Integer>();
for(int i = 0;i < points.length;i++) {
int dup = 1;
map.clear();
for(int j = i + 1;j < points.length;j++) {
int dx = points[j][0] - points[i][0], dy = points[j][1] - points[i][1];
if(dx == 0 && dy == 0)dup++;
else {
int gcd = getGcd(dx, dy);
long slope = ((long)(dy / gcd) << 32) + (dx / gcd);
map.put(slope, map.getOrDefault(slope, 0) + 1);
}
}
max = Math.max(max, dup);
for(Map.Entry<Long, Integer> entry : map.entrySet())
max = Math.max(max, entry.getValue() + dup);
}
return max;
}
int getGcd(int a, int b) {
return b == 0 ? a : getGcd(b, a % b);
}
}
fishercoder1534 commented
Good catch!
LGTM, do you want to submit a new PR instead of issue to update the solution?