Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Editorial] Max points on a line #4572

Merged
merged 16 commits into from
Jul 4, 2024
13 changes: 13 additions & 0 deletions content/5_Plat/Geo_Pri.problems.json
Original file line number Diff line number Diff line change
Expand Up @@ -145,12 +145,25 @@
"kind": "internal"
}
},
{
"uniqueId": "leetcode-149",
"name": "Max Points on a Line",
"url": "https://leetcode.com/problems/max-points-on-a-line/description/",
"source": "Leetcode",
"difficulty": "Easy",
"isStarred": false,
"tags": [],
"solutionMetadata": {
"kind": "internal"
}
},
{
"uniqueId": "ioi-02-frog",
"name": "The Troublesome Frog",
"url": "https://ioi.contest.codeforces.com/group/32KGsXgiKA/contest/103699/problem/A",
"source": "IOI",
"difficulty": "Normal",

"isStarred": false,
"tags": [],
"solutionMetadata": {
Expand Down
56 changes: 56 additions & 0 deletions solutions/platinum/leetcode-149.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
---
id: leetcode-149
source: Leetcode
title: Max Points on a Line
author: Mihnea Brebenel
---

## Explanation

Because $n \le 300$ we can naively go through all pairs of points and check how many other points are collinear with them.
Three points $A$, $B$, and $C$ are collinear if and only if $AB$ has the same slope as $BC$:

$$
\frac{A_y-B_y}{A_x-B_x}=\frac{B_y-C_y}{B_x-C_x}
$$

In practice you'll find this formula in a product form to avoid dealing with floating-point values.

## Implementation

**Time Complexity:** $\mathcal{O}(n^3)$

<LanguageSection>
<CPPSection>

```cpp
class Solution {
public:
int maxPoints(vector<vector<int>> &points) {
if (points.size() <= 2) { return points.size(); }

int ans = 0;
for (int i = 0; i < points.size(); i++) {
for (int j = i + 1; j < points.size(); j++) {
int p = 2; // the 2 points are collinear with themselves
for (int k = j + 1; k < points.size(); k++) {
int dx1 = points[i][0] - points[k][0],
dx2 = points[j][0] - points[i][0];
int dy1 = points[i][1] - points[k][1],
dy2 = points[j][1] - points[i][1];
// Check if dy1 / dx1 = dy2 / dx2
// Which is the same as: dy1 * dx2 = dy2 * dx1
if (dy1 * dx2 == dy2 * dx1) { p++; }
}

ans = max(ans, p);
}
}

return ans;
}
};
```

</CPPSection>
</LanguageSection>
Loading