[LeetCode] Max Points on a Line

149. Max Points on a Line

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane, return the maximum number of points that lie on the same straight line.

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
class Solution {
int gcd(int p, int q) {
return !q ? p : gcd(q, p % q);
}
pair<int, int> getInclinations(vector<int>& a, vector<int>& b) {
int dx = a[1] - b[1];
int dy = a[0] - b[0];
if(!dx) return {1, 0};
if(!dy) return {0, 1};
int sign = dx * dy < 0 ? -1 : 1;
dx = abs(dx), dy = abs(dy);
int GCD = gcd(dx, dy);
return {sign * dy / GCD, dx / GCD};
}
public:
int maxPoints(vector<vector<int>>& points) {
int n = points.size(), res = 1;
for(int i = 0; i < n; i++) {
map<pair<int, int>, int> table;
for(int j = i + 1; j < n; j++) {
pair<int, int> inc = getInclinations(points[i], points[j]);
res = max(res, ++table[inc] + 1);
}
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/08/PS/LeetCode/max-points-on-a-line/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.