Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Solution:
/**
* Definition for a point.
* type Point struct {
* X int
* Y int
* }
*/
func maxPoints(points []Point) int {
max := 0
l := len(points)
for i := 0; i < l; i++ {
for j := i + 1; j < l; j++ {
p1 := points[i]
p2 := points[j]
dx := p1.X - p2.X
dy := p1.Y - p2.Y
if dx == 0 && dy == 0 {
continue
}
cnt := 0
for _, p := range points {
_x := p.X - p2.X
_y := p.Y - p2.Y
if _x*dy == _y*dx {
cnt++
}
}
if cnt > max {
max = cnt
}
}
}
if max == 0 {
return len(points)
}
return max
}