forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.php
39 lines (35 loc) · 916 Bytes
/
Solution.php
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
class Solution {
/**
* @param integer[] $height
* @return integer
*/
function trap($height) {
$n = count($height);
if ($n == 0) {
return 0;
}
$left = 0;
$right = $n - 1;
$leftMax = 0;
$rightMax = 0;
$ans = 0;
while ($left < $right) {
if ($height[$left] < $height[$right]) {
if ($height[$left] > $leftMax) {
$leftMax = $height[$left];
} else {
$ans += $leftMax - $height[$left];
}
$left++;
} else {
if ($height[$right] > $rightMax) {
$rightMax = $height[$right];
} else {
$ans += $rightMax - $height[$right];
}
$right--;
}
}
return $ans;
}
}