Max Points on a Line
Total Accepted: 289 Total Submissions: 3644Given 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) {}
* };
*/
class Solution {
public:
int maxPoints(vector<Point> &points) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
map<float, int> kmap;
map<float, int>::iterator it;
int size = points.size();
int total = 0;
int sum_cloumn = 0;
if(size<=2)
return size;
for(int i=0;i<size;i++)
{
sum_cloumn = 0;
int add=1;
kmap.clear();
for(int j=0;j<size;j++)
{
if(j==i)
continue;
if(points[i].x==points[j].x && points[i].y==points[j].y)
{
add++;
continue ;
}
float k = 0;
if(points[i].x!=points[j].x)
{
k = (float)(points[j].y-points[i].y)/(points[j].x-points[i].x);
if(kmap.find(k)!=kmap.end())
{
kmap[k]++;
}
else
{
kmap[k] = 1;
}
}else{
sum_cloumn++;
}
}
for(it=kmap.begin(); it!=kmap.end();it++)
{
if(it->second > sum_cloumn)
sum_cloumn = it->second;
}
sum_cloumn += add;
if(sum_cloumn > total)
total = sum_cloumn;
}
return total;
}
};