42. Trapping Rain Water #47
Answered
by
mah-shamim
mah-shamim
asked this question in
Q&A
-
|
Given Example 1:
Example 2:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Answered by
mah-shamim
Jul 31, 2024
Replies: 1 comment
-
|
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 42. Trapping Rain Water <?php
function trap($height) {
$n = count($height);
if ($n == 0) return 0;
$left = 0;
$right = $n - 1;
$left_max = 0;
$right_max = 0;
$water = 0;
while ($left <= $right) {
if ($height[$left] <= $height[$right]) {
if ($height[$left] >= $left_max) {
$left_max = $height[$left];
} else {
$water += $left_max - $height[$left];
}
$left++;
} else {
if ($height[$right] >= $right_max) {
$right_max = $height[$right];
} else {
$water += $right_max - $height[$right];
}
$right--;
}
}
return $water;
}
// Example usage:
$height = [0,1,0,2,1,0,1,3,2,1,2,1];
echo trap($height); // Output: 6
$height = [4,2,0,3,2,5];
echo trap($height); // Output: 9
?>Explanation:
This approach efficiently computes the amount of trapped rainwater by leveraging the two-pointer technique and avoids the need for additional space, making it optimal for large input sizes. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
kovatz
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment

To solve this problem, we can follow these steps:
leftstarting at the beginning andrightat the end of the elevation array.left_maxandright_maxto track the maximum heights encountered from the left and right sides, respectively.left_maxandright_max.Let's implement this solution in PHP: 42. Trapping Rain Water