-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathMaximumPointsInAStraightLine.java
More file actions
95 lines (75 loc) · 2.33 KB
/
MaximumPointsInAStraightLine.java
File metadata and controls
95 lines (75 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
Sample Input :
(1, 1)
(2, 2)
Sample Output :
2
You will be given 2 arrays X and Y. Each point is represented by (X[i], Y[i])
**/
public class Solution
{
public int maxPoints(ArrayList<Integer> a, ArrayList<Integer> b)
{
int length1 = a.size();
int length2 = b.size();
int maximum = 0;
Map<Double, Integer> map = new HashMap<Double, Integer>();
if(length1 != length2 || length1 == 0 || a == null || length2 == 0 || b == null)
{
return maximum;
}
if(length1 == 1 && length2 == 1) return 1;
for(int i=0; i<length1; i++)
{
int vertical = 0;
int duplicate = 1;
int xi = a.get(i);
int yi = b.get(i);
for(int j=i+1; j<length2; j++)
{
int xj = a.get(j);
int yj = b.get(j);
if(xi == xj)
{
if(yi == yj)
{
duplicate++;
}
else
{
vertical++;
}
}
else
{
double slope = 0.0;
if(yj - yi == 0)
slope = 0.0;
else
{
slope = (double)(yj - yi)/(double)(xj - xi);
}
if(!map.containsKey(slope))
{
map.put(slope, 1);
}
else
{
map.put(slope, map.get(slope)+1);
}
}
}
for(int value : map.values())
{
if(value + duplicate > maximum)
{
maximum = value + duplicate;
}
}
maximum = Math.max(vertical + duplicate, maximum);
map.clear();
}
return maximum;
}
}