To solve this problem, we need to determine the maximum number of points that lie on the same straight line given an array of points. The solution involves calculating slopes between points to identify lines and handling edge cases like duplicate points, vertical lines, and floating-point precision issues.
import math
from collections import defaultdict
def max_points(points):
if len(points) <= 1:
return len(points)
max_p = 0
for i in range(len(points)):
slope_dict = defaultdict(int)
duplicates = 1
current_max = 0
x1, y1 = points[i]
for j in range(len(points)):
if i == j:
continue
x2, y2 = points[j]
# Count duplicate points
if x1 == x2 and y1 == y2:
duplicates += 1
continue
dy = y2 - y1
dx = x2 - x1
# Handle vertical lines (undefined slope)
if dx == 0:
key = ('inf',)
else:
# Reduce dy/dx to simplest form
gcd_val = math.gcd(abs(dy), abs(dx))
reduced_dy = dy // gcd_val
reduced_dx = dx // gcd_val
# Ensure consistent sign for the denominator
if reduced_dx < 0:
reduced_dy *= -1
reduced_dx *= -1
key = (reduced_dy, reduced_dx)
slope_dict[key] += 1
current_max = max(current_max, slope_dict[key])
# Total points on the line: duplicates + points with same slope
total = duplicates + current_max
max_p = max(max_p, total)
return max_p
This approach effectively handles all edge cases and ensures accurate results using integer arithmetic to avoid floating-point errors. It is robust and efficient for the given problem.
(免責聲明:本文為本網站出于傳播商業(yè)信息之目的進行轉載發(fā)布,不代表本網站的觀點及立場。本文所涉文、圖、音視頻等資料的一切權利和法律責任歸材料提供方所有和承擔。本網站對此資訊文字、圖片等所有信息的真實性不作任何保證或承諾,亦不構成任何購買、投資等建議,據此操作者風險自擔。) 本文為轉載內容,授權事宜請聯(lián)系原著作權人,如有侵權,請聯(lián)系本網進行刪除。