Skip to content

42. Trapping Rain Water #47

Answered by mah-shamim
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

To solve this problem, we can follow these steps:

  1. Initialize two pointers: left starting at the beginning and right at the end of the elevation array.
  2. Track maximum heights: Use left_max and right_max to track the maximum heights encountered from the left and right sides, respectively.
  3. Move pointers towards each other: At each step, move the pointer with the smaller height inward and update the trapped water amount based on the minimum of left_max and right_max.

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

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested hard Difficulty
1 participant