From 74d3c1cc6760e71164fc2b87bc2b2448830ab36d Mon Sep 17 00:00:00 2001 From: Yeongrok Jeong Date: Tue, 23 May 2023 02:28:20 +0900 Subject: [PATCH 1/2] Create README - LeetHub --- yeongrok/0042-trapping-rain-water/README.md | 25 +++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 yeongrok/0042-trapping-rain-water/README.md 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 @@ +

42. Trapping Rain Water

Hard


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:

+ + +
\ No newline at end of file From 9eef6e95d7ae39c022c23f790836ee8b2f804a1e Mon Sep 17 00:00:00 2001 From: yeongrok-jeong Date: Tue, 23 May 2023 02:30:35 +0900 Subject: [PATCH 2/2] Time: 51 ms (99.40%), Space: 42.8 MB (86.14%) - LeetHub --- .../0042-trapping-rain-water.js | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 yeongrok/0042-trapping-rain-water/0042-trapping-rain-water.js 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; +};