1+ import
2+
3+ fun maximumCollinearPoints (points : List <List <Int >>): Int {
4+ var res = 0
5+ // Treat each point as a focal point, and determine the maximum
6+ // number of points that are collinear with each focal point. The
7+ // largest of these maximums is the answer.
8+ for (i in points.indices) {
9+ res = maxOf(res, maxPointsFromFocalPoint(i, points))
10+ }
11+ return res
12+ }
13+
14+ fun maxPointsFromFocalPoint (focalPointIndex : Int , points : List <List <Int >>): Int {
15+ val slopesMap = mutableMapOf<Pair <Int , Int >, Int > ()
16+ var maxPoints = 0
17+ // For the current focal point, calculate the slope between it and
18+ // every other point. This allows us to group points that share the
19+ // same slope.
20+ for (j in points.indices) {
21+ if (j != focalPointIndex) {
22+ val currSlope = getSlope(points[focalPointIndex], points[j])
23+ slopesMap[currSlope] = slopesMap.getOrDefault(currSlope, 0 ) + 1
24+ // Update the maximum count of collinear points for the
25+ // current focal point.
26+ maxPoints = maxOf(maxPoints, slopesMap[currSlope]!! )
27+ }
28+ }
29+ // Add 1 to the maximum count to include the focal point itself.
30+ return maxPoints + 1
31+ }
32+
33+ fun getSlope (p1 : List <Int >, p2 : List <Int >): Pair <Int , Int > {
34+ val rise = p2[1 ] - p1[1 ]
35+ val run = p2[0 ] - p1[0 ]
36+ // Handle vertical lines separately to avoid dividing by 0.
37+ if (run == 0 ) {
38+ return Pair (1 , 0 )
39+ }
40+ // Simplify the slope to its reduced form.
41+ val gcdVal = gcd(rise, run)
42+ return Pair (rise / gcdVal, run / gcdVal)
43+ }
44+
45+ // Kotlin doesn't have a built-in GCD function, so we define one here.
46+ fun gcd (a : Int , b : Int ): Int {
47+ var num1 = a
48+ var num2 = b
49+ while (num2 != 0 ) {
50+ val temp = num2
51+ num2 = num1 % num2
52+ num1 = temp
53+ }
54+ return num1
55+ }
0 commit comments