Skip to content

Instantly share code, notes, and snippets.

@croespino
Last active April 23, 2023 02:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save croespino/76af6af9e1c259f0b442aff877108e84 to your computer and use it in GitHub Desktop.
Save croespino/76af6af9e1c259f0b442aff877108e84 to your computer and use it in GitHub Desktop.
function maxPointsOnLine(points: number[][]): number {
if (points.length === 1) {
return 1;
}
const pointPairs = [];
for (let i = 0; i < points.length; i++) {
for (let j = i + 1; j < points.length; j++) {
pointPairs.push([points[i][0], points[i][1], points[j][0], points[j][1]]);
}
}
let maxPointsOnStraightLine = 0;
for (const [x1, y1, x2, y2] of pointPairs) {
let pointsCount = 2;
for (const point of points) {
const [x3, y3] = point;
if ((x3 === x1 && y3 === y1) || (x3 === x2 && y3 === y2)) {
continue;
}
// Given two points, verify whether the third point is collinear
if (((y2 - y1) / (x2 - x1)) === ((y3 - y1) / (x3 - x1))) {
pointsCount++;
}
}
maxPointsOnStraightLine = Math.max(maxPointsOnStraightLine, pointsCount);
}
return maxPointsOnStraightLine;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment