-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0149-max-points-on-a-line.js
More file actions
51 lines (41 loc) · 1.53 KB
/
0149-max-points-on-a-line.js
File metadata and controls
51 lines (41 loc) · 1.53 KB
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
/**
* Max Points On A Line
* Time Complexity: O(N^2)
* Space Complexity: O(N)
*/
var maxPoints = function (points) {
const pointsArrayLength = points.length;
if (pointsArrayLength <= 2) {
return pointsArrayLength;
}
let globalMaximumPoints = 0;
for (let pivotIndex = 0; pivotIndex < pointsArrayLength; pivotIndex++) {
const currentPivotPoint = points[pivotIndex];
const slopeRegistry = new Map();
let identicalCoordinatePoints = 1;
let verticalLinePoints = 0;
for (let otherPointIndex = pivotIndex + 1; otherPointIndex < pointsArrayLength; otherPointIndex++) {
const comparedPoint = points[otherPointIndex];
const deltaXValue = comparedPoint[0] - currentPivotPoint[0];
const deltaYValue = comparedPoint[1] - currentPivotPoint[1];
if (deltaXValue === 0 && deltaYValue === 0) {
identicalCoordinatePoints++;
continue;
}
if (deltaXValue === 0) {
verticalLinePoints++;
continue;
}
const calculatedSlope = deltaYValue / deltaXValue;
const currentSlopeCount = (slopeRegistry.get(calculatedSlope) || 0) + 1;
slopeRegistry.set(calculatedSlope, currentSlopeCount);
}
let currentPivotMax = 0;
for (const countedPoints of slopeRegistry.values()) {
currentPivotMax = Math.max(currentPivotMax, countedPoints);
}
currentPivotMax = Math.max(currentPivotMax, verticalLinePoints);
globalMaximumPoints = Math.max(globalMaximumPoints, currentPivotMax + identicalCoordinatePoints);
}
return globalMaximumPoints;
};