forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMax Points on a Line.js
58 lines (43 loc) · 1.29 KB
/
Max Points on a Line.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* @param {number[][]} points
* @return {number}
*/
var maxPoints = function(points) {
if (points.length === 1) {
return 1;
}
const slopes = {};
let dx, dy;
let xbase, ybase;
let xref, yref, key;
const INFINITE_SLOPE = 'infinite';
for(let i = 0; i < points.length; i++) {
[xbase, ybase] = points[i];
for(let j = i + 1; j < points.length; j++) {
[xref, yref] = points[j];
if (xref === xbase) {
key = `x = ${xref}`;
} else {
dx = xref - xbase;
dy = yref - ybase;
let m = dy / dx;
let c = yref - m * xref;
m = m.toFixed(4);
c = c.toFixed(4);
key = `y = ${m}x + ${c}`;
}
slopes[key] || (slopes[key] = 0);
slopes[key]++;
}
}
const maxPairs = Math.max(...Object.values(slopes));
if (maxPairs === 2) {
return 2;
}
for(let i = 1; i <= 300; i++) {
if (i * (i - 1) / 2 === maxPairs) {
return i;
}
}
return 0;
};