Skip to content

Commit 2be3f0e

Browse files
authored
Create 149-max-points-on-a-line.js
1 parent 760709b commit 2be3f0e

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

149-max-points-on-a-line.js

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* @param {number[][]} points
3+
* @return {number}
4+
*/
5+
const maxPoints = function (points) {
6+
if (points.length < 2 || points == null) return points.length
7+
let max = 2
8+
for (let i = 0; i < points.length; i++) {
9+
let [p1x, p1y] = points[i]
10+
let samePoint = 1,
11+
map = { base: 0 } // to avoid when map = {}, the max value is -Infinity
12+
for (let j = i + 1; j < points.length; j++) {
13+
if (points[i][0] == points[j][0] && points[i][1] == points[j][1]) {
14+
samePoint++
15+
} else {
16+
let [p2x, p2y] = points[j]
17+
let slope = (1000000.0 * (p2y - p1y)) / (p2x - p1x)
18+
if (!Number.isFinite(slope)) slope = 'v'
19+
else if (Number.isNaN(slope)) slope = 'h'
20+
map[slope] = map[slope] + 1 || 1
21+
}
22+
}
23+
max = Math.max(Math.max(...Object.values(map)) + samePoint, max)
24+
}
25+
return max
26+
}

0 commit comments

Comments
 (0)