Skip to content

Commit 42cf38f

Browse files
committed
Sync LeetCode submission Runtime - 18 ms (44.05%), Memory - 19.2 MB (56.11%)
1 parent e7e8311 commit 42cf38f

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

0042-trapping-rain-water/README.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<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>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img src="https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" style="width: 412px; height: 161px;" />
6+
<pre>
7+
<strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1]
8+
<strong>Output:</strong> 6
9+
<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.
10+
</pre>
11+
12+
<p><strong class="example">Example 2:</strong></p>
13+
14+
<pre>
15+
<strong>Input:</strong> height = [4,2,0,3,2,5]
16+
<strong>Output:</strong> 9
17+
</pre>
18+
19+
<p>&nbsp;</p>
20+
<p><strong>Constraints:</strong></p>
21+
22+
<ul>
23+
<li><code>n == height.length</code></li>
24+
<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>
25+
<li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li>
26+
</ul>
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Approach 4: Using 2 pointers
2+
3+
# Time: O(n)
4+
# Space: O(1)
5+
6+
class Solution:
7+
def trap(self, height: List[int]) -> int:
8+
left, right = 0, len(height) - 1
9+
ans = 0
10+
left_max, right_max = 0, 0
11+
12+
while left < right:
13+
if height[left] < height[right]:
14+
left_max = max(left_max, height[left])
15+
ans += left_max - height[left]
16+
left += 1
17+
else:
18+
right_max = max(right_max, height[right])
19+
ans += right_max - height[right]
20+
right -= 1
21+
22+
return ans

0 commit comments

Comments
 (0)