LeetCode 0149. Max Points on a Line Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0149. Max Points on a Line

Description

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:

Input: points = [[1,1],[2,2],[3,3]]
Output: 3

Example 2:

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.

Solutions

Solution 1

PythonJavaC++GoC#
class Solution: def maxPoints(self, points: List[List[int]]) -> int: n = len(points) ans = 1 for i in range(n): x1, y1 = points[i] for j in range(i + 1, n): x2, y2 = points[j] cnt = 2 for k in range(j + 1, n): x3, y3 = points[k] a = (y2 - y1) * (x3 - x1) b = (y3 - y1) * (x2 - x1) cnt += a == b ans = max(ans, cnt) return ans(code-box)

Solution 2

PythonJavaC++Go
class Solution: def maxPoints(self, points: List[List[int]]) -> int: def gcd(a, b): return a if b == 0 else gcd(b, a % b) n = len(points) ans = 1 for i in range(n): x1, y1 = points[i] cnt = Counter() for j in range(i + 1, n): x2, y2 = points[j] dx, dy = x2 - x1, y2 - y1 g = gcd(dx, dy) k = (dx // g, dy // g) cnt[k] += 1 ans = max(ans, cnt[k] + 1) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !