Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f5e9e7d

Browse files
committed
Add solution 149.
1 parent 78e0067 commit f5e9e7d

File tree

1 file changed

+98
-0
lines changed

1 file changed

+98
-0
lines changed
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/**
2+
* Definition for a point.
3+
* class Point(
4+
* public $x = 0;
5+
* public $y = 0;
6+
* function __construct(int $x = 0, int $y = 0) {
7+
* $this->x = $x;
8+
* $this->y = $y;
9+
* }
10+
* )
11+
*/
12+
class Solution {
13+
14+
/**
15+
* @param Point[] $points
16+
* @return Integer
17+
*/
18+
function maxPoints($points) {
19+
$max = 0;
20+
$duplicated = 0;
21+
$isMaxChanged = false;
22+
if ($points == null || count($points) == 0) {
23+
return 0;
24+
} else if (count($points) == 1) {
25+
return 1;
26+
} else if (count($points) == 2) {
27+
return 2;
28+
} else {
29+
for ($i=0;$i<count($points);$i++) {
30+
//key is a string = y + "/" + x to prevent from division/float/double/BigDecimal
31+
//value is amount of points on the same line -1
32+
$amount = [];
33+
//j=i+1 to prevent from backwarding loop
34+
for ($j=$i+1;$j<count($points);$j++) {
35+
$y = $points[$j]->y - $points[$i]->y;
36+
$x = $points[$j]->x - $points[$i]->x;
37+
38+
if ($x == 0 && $y == 0) {
39+
$duplicated++;
40+
if ($isMaxChanged == true) {
41+
$max++;
42+
} else if ($max < $duplicated) {
43+
$max = $duplicated;
44+
}
45+
46+
} else {
47+
$gcd = self::getGCD($y,$x);
48+
if ($gcd != 0) {
49+
$y = intval($y / $gcd);
50+
$x = intval($x / $gcd);
51+
$k = $y."/".$x;
52+
if (array_key_exists($k, $amount)) {
53+
$n = $amount[$k];
54+
$amount[$k] = $n+1;
55+
if ($max < $n+1+$duplicated) {
56+
$max = $n+1+$duplicated;
57+
$isMaxChanged = true;
58+
}
59+
} else {
60+
$amount[$k] = 1;
61+
if ($max < 1+$duplicated) {
62+
$max = 1+$duplicated;
63+
$isMaxChanged = true;
64+
}
65+
}
66+
}
67+
}
68+
}
69+
70+
$duplicated = 0;
71+
$isMaxChanged = false;
72+
73+
}
74+
return $max+1;
75+
}
76+
}
77+
78+
//horizontal lines make x=0 & y=1
79+
//vertical lines make x=1 & y=0
80+
//same position points should not invoke this function whick make x=0 & y=0
81+
//other points return the gcd
82+
function getGCD($y, $x) {
83+
if ($x == 0) {
84+
if ($y == 0) {
85+
return 0;//same point
86+
} else {
87+
return $y;//horizontal lines
88+
}
89+
} else {
90+
//normal case and the vertical lines
91+
if ($y%$x != 0) {
92+
return self::getGCD($x,$y%$x);
93+
} else {
94+
return $x;
95+
}
96+
}
97+
}
98+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /