forked from spring1843/go-dsa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmax_points_on_line.go
49 lines (43 loc) · 910 Bytes
/
max_points_on_line.go
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
package hashtable
import "math"
// MaxPointsOnALine runs in O(n^2) time and O(n) space.
func MaxPointsOnALine(points [][]int) int {
if len(points) <= 2 {
return len(points)
}
maxPoints := 1
for i, point := range points {
samePoint := 0
localMax := 1
slopeCount := make(map[float64]int)
for j := i + 1; j < len(points); j++ {
if isSame(point, points[j]) {
samePoint++
continue
}
slope := calculateSlope(point, points[j])
slopeCount[slope]++
localMax = max(localMax, slopeCount[slope])
}
maxPoints = max(maxPoints, localMax+samePoint+1)
}
return maxPoints
}
func isSame(a, b []int) bool {
return a[0] == b[0] && a[1] == b[1]
}
func calculateSlope(a, b []int) float64 {
if a[0] == b[0] {
return math.MaxFloat64
}
if a[1] == b[1] {
return 1
}
return float64(a[1]-b[1]) / float64(a[0]-b[0])
}
func max(a, b int) int {
if a > b {
return a
}
return b
}