diff --git a/yeongrok/0042-trapping-rain-water/0042-trapping-rain-water.js b/yeongrok/0042-trapping-rain-water/0042-trapping-rain-water.js new file mode 100644 index 0000000..f7b1ec9 --- /dev/null +++ b/yeongrok/0042-trapping-rain-water/0042-trapping-rain-water.js @@ -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; +}; diff --git a/yeongrok/0042-trapping-rain-water/README.md b/yeongrok/0042-trapping-rain-water/README.md new file mode 100644 index 0000000..9d727dd --- /dev/null +++ b/yeongrok/0042-trapping-rain-water/README.md @@ -0,0 +1,25 @@ +
Given n
non-negative integers representing an elevation map where the width of each bar is 1
, compute how much water it can trap after raining.
+
Example 1:
+Input: height = [0,1,0,2,1,0,1,3,2,1,2,1] +Output: 6 +Explanation: 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. ++ +
Example 2:
+ +Input: height = [4,2,0,3,2,5] +Output: 9 ++ +
+
Constraints:
+ +n == height.length
1 <= n <= 2 * 104
0 <= height[i] <= 105