Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
/** Definition for a point. * struct Point {* int x; * int y; * Point (): X (0), y (0) {} * point (int a , int B): X (a), Y (b) {}}; */classSolution { Public: intMaxpoints (Vector<point> &points) { if(Points.size () <=2)//equal to 2 then just return size returnpoints.size (); Unordered_map<string,int>Dupmap; for(inti =0; I < points.size (); i++) {//Delete dubs and keep track of their count in Dupmap stringPT = to_string (points[i].x) +' '+to_string (POINTS[I].Y); if(Dupmap.count (pt) = =0) dupmap[pt]=0; Else{dupmap[pt]++; Points.erase (Points.begin ()+ i--); } } if(points.size () = =1){//if every item was a DUP stringPT = to_string (points[0].x) +' '+ to_string (points[0].y); returnDUPMAP[PT] +1; } intMax =2; for(inti =0; I < points.size ()-1; i++) {//O (n^2) Calclate every combination of pointsunordered_map<string,int>HashMap; stringPT = to_string (points[i].x) +' '+to_string (POINTS[I].Y); for(intj = i+1; J < Points.size (); J + +){ stringPt2 = to_string (points[j].x) +' '+to_string (POINTS[J].Y); stringEQ =""; if(points[i].x = =points[j].x) EQ="x ="+ to_string (points[i].x);//infinte Slope Else{ floatm = (float) (POINTS[J].Y-POINTS[I].Y)/(float) (points[j].x-points[i].x);//Slopem = (M <0.0005&& m >-0.0005)?0: M;//rounding to 0 for floats floatB = (float) Points[i].y-(float) (M *points[i].x); EQ="y ="+ to_string (m) +'+'+ to_string (b);//form equation String } if(Hashmap.count (eq) = =0){//havent seen this eq beforeHASHMAP[EQ] =2; if(Dupmap[pt] >0)//PT has dupesHASHMAP[EQ] + =DUPMAP[PT]; if(Dupmap[pt2] >0)//Pt2 has dupesHASHMAP[EQ] + =DUPMAP[PT2]; } ElseHashmap[eq]+ = (Dupmap[pt2] >0)? DUPMAP[PT2] +1:1; Max= (Hashmap[eq] > max)?Hashmap[eq]: max; } } returnMax//return the max Count }};
Max Points on a line