imashutosh51

Maximum points on a line

Oct 29th, 2022 (edited)
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.22 KB | None | 0 0
  1. '''
  2. Logic:
  3. We can find the slope of line from two points by slope=(y2-y1)/(x2-x1).
  4. We will iterate through the points and consider all the pairs of points.
  5. There is one temporary map which will store the slope count for every pairs
  6. for each ith iteration and finally pairs with maximum points of same slope
  7. will be the answer.
  8.  
  9. Trick: There is one catch that when line will be vertical then (x2-x1) ie. denominator
  10. will be 0 so we are managing vertical lines using a temporary variable.
  11. '''
  12.  
  13. class Solution:
  14.     def maxPoints(self, points: List[List[int]]) -> int:
  15.         points=sorted(points)
  16.         ans=0
  17.         for i in range(len(points)):
  18.             dict={}
  19.             temp=0
  20.             for j in range(i+1,len(points)):
  21.                 x1,y1=points[i][0],points[i][1]
  22.                 x2,y2=points[j][0],points[j][1]
  23.                 if x2-x1==0:
  24.                     temp+=1
  25.                 else:
  26.                     slope=(y2-y1)/(x2-x1)
  27.                     if slope in dict.keys():
  28.                         dict[slope]+=1
  29.                     else:
  30.                         dict[slope]=1
  31.                     ans=max(ans,dict[slope])
  32.             ans=max(ans,temp)
  33.         return max(ans,temp)+1;
  34.         ;
Advertisement
Add Comment
Please, Sign In to add comment