Skip to content

42. Trapping Rain Water / Hard / JavaScript #54

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions yeongrok/0042-trapping-rain-water/0042-trapping-rain-water.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/**
* @param {number[]} height
* @return {number}
*/
var trap = function (height) {
if (height.length <= 2) return 0;

let left = 0;
let right = height.length - 1;
let maxLeftHeight = 0;
let maxRightHeight = 0;
let totalWater = 0;

while (left < right) {
if (height[left] < height[right]) {
if (height[left] >= maxLeftHeight) {
maxLeftHeight = height[left];
} else {
totalWater += maxLeftHeight - height[left];
}
left++;
} else {
if (height[right] >= maxRightHeight) {
maxRightHeight = height[right];
} else {
totalWater += maxRightHeight - height[right];
}
right--;
}
}

return totalWater;
};
25 changes: 25 additions & 0 deletions yeongrok/0042-trapping-rain-water/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<h2><a href="https://leetcode.com/problems/trapping-rain-water/">42. Trapping Rain Water</a></h2><h3>Hard</h3><hr><div><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>
</div>