<p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img src="https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" style="width: 412px; height: 161px;" />
<pre>
<strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1]
<strong>Output:</strong> 6
<strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> height = [4,2,0,3,2,5]
<strong>Output:</strong> 9
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>n == height.length</code></li>
	<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution {
public:
    int trap(vector<int>& height) {
        /*
        int trapped = 0; 
        vector <int> maxLeft; 
        vector<int> maxRight (height.size()); 

        int l= 0; 

        for (int i {}; i < height.size(); i++){
            maxLeft.push_back(l);
            l = max(l, height[i]);
        }

        int r = height[height.size()-1];

        for (int i = height.size() - 1; i >= 0; i--){
            maxRight[i] = r; 
            r = max(r, height[i]);
        }

        for (int i {}; i < height.size(); i++){
            int water = min(maxLeft[i], maxRight[i]) - height[i];
            if (water < 0) {
                water = 0; 
            }
            trapped += water;
        }

        return trapped;
        */
        int trapped = 0;

        int l = 0; 
        int r = height.size() - 1; 

        int maxL = height[l];
        int maxR = height[r]; 

        while (l < r){ 
            if (maxL < maxR){ 
                l++; 
                maxL = max(maxL, height[l]); 
                if ((maxL - height[l]) < 0 ){
                    continue;
                }
                trapped += maxL - height[l];
            } else {
                r--; 
                maxR = max(maxR, height[r]); 
                if ((maxR - height[r]) < 0 ){
                    continue;
                }
                trapped += maxR - height[r];
            }
        }

        return trapped;
        
    }
};
24500