g0101_0200.s0149_max_points_on_a_line.Solution Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-java21 Show documentation
Show all versions of leetcode-in-java21 Show documentation
Java-based LeetCode algorithm problem solutions, regularly updated
package g0101_0200.s0149_max_points_on_a_line;
// #Hard #Top_Interview_Questions #Array #Hash_Table #Math #Geometry #Algorithm_II_Day_21_Others
// #2022_06_24_Time_11_ms_(99.21%)_Space_41.5_MB_(95.53%)
/**
* 149 - Max Points on a Line\.
*
* Hard
*
* 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_.
*
* **Example 1:**
*
* ![](https://assets.leetcode.com/uploads/2021/02/25/plane1.jpg)
*
* **Input:** points = \[\[1,1],[2,2],[3,3]]
*
* **Output:** 3
*
* **Example 2:**
*
* ![](https://assets.leetcode.com/uploads/2021/02/25/plane2.jpg)
*
* **Input:** points = \[\[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]]
*
* **Output:** 4
*
* **Constraints:**
*
* * `1 <= points.length <= 300`
* * `points[i].length == 2`
* * -104 <= xi, yi <= 104
* * All the `points` are **unique**.
**/
public class Solution {
public int maxPoints(int[][] points) {
if (points.length < 2) {
return points.length;
}
int max = 0;
for (int i = 0; i < points.length; i++) {
for (int j = i + 1; j < points.length; j++) {
int x = points[j][0] - points[i][0];
int y = points[j][1] - points[i][1];
int c = x * points[j][1] - y * points[j][0];
int count = 2;
for (int k = j + 1; k < points.length; k++) {
if (c == x * points[k][1] - y * points[k][0]) {
count++;
}
}
max = Math.max(count, max);
}
}
return max;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy