1
+ #include < vector>
2
+ #include < map>
3
+ #include < utility>
4
+ #include < algorithm>
5
+ #include < numeric>
6
+
7
+ int maximumCollinearPoints (std::vector<std::vector<int >>& points) {
8
+ int res = 0 ;
9
+ // Treat each point as a focal point, and determine the maximum
10
+ // number of points that are collinear with each focal point. The
11
+ // largest of these maximums is the answer.
12
+ for (int i = 0 ; i < points.size (); i++) {
13
+ res = std::max (res, maxPointsFromFocalPoint (i, points));
14
+ }
15
+ return res;
16
+ }
17
+
18
+ int maxPointsFromFocalPoint (int focalPointIndex, std::vector<std::vector<int >>& points) {
19
+ std::map<std::pair<int , int >, int > slopesMap;
20
+ int maxPoints = 0 ;
21
+ // For the current focal point, calculate the slope between it and
22
+ // every other point. This allows us to group points that share the
23
+ // same slope.
24
+ for (int j = 0 ; j < points.size (); j++) {
25
+ if (j != focalPointIndex) {
26
+ std::pair<int , int > currSlope = getSlope (points[focalPointIndex], points[j]);
27
+ slopesMap[currSlope]++;
28
+ // Update the maximum count of collinear points for the
29
+ // current focal point.
30
+ maxPoints = std::max (maxPoints, slopesMap[currSlope]);
31
+ }
32
+ }
33
+ // Add 1 to the maximum count to include the focal point itself.
34
+ return maxPoints + 1 ;
35
+ }
36
+
37
+ std::pair<int , int > getSlope (std::vector<int >& p1, std::vector<int >& p2) {
38
+ int rise = p2[1 ] - p1[1 ];
39
+ int run = p2[0 ] - p1[0 ];
40
+ // Handle vertical lines separately to avoid dividing by 0.
41
+ if (run == 0 ) {
42
+ return {1 , 0 };
43
+ }
44
+ // Simplify the slope to its reduced form.
45
+ int gcdVal = std::gcd (rise, run);
46
+ return {rise / gcdVal, run / gcdVal};
47
+ }
0 commit comments