|
| 1 | +# 42. [Trapping Rain Water](<https://leetcode.com/problems/trapping-rain-water>) |
| 2 | + |
| 3 | +*All prompts are owned by LeetCode. To view the prompt, click the title link above.* |
| 4 | + |
| 5 | +*[Back to top](<../README.md>)* |
| 6 | + |
| 7 | +------ |
| 8 | + |
| 9 | +> *First completed : March 11, 2025* |
| 10 | +> |
| 11 | +> *Last updated : March 11, 2025* |
| 12 | +
|
| 13 | +------ |
| 14 | + |
| 15 | +> **Related Topics** : **[Array](<by_topic/Array.md>), [Two Pointers](<by_topic/Two Pointers.md>), [Dynamic Programming](<by_topic/Dynamic Programming.md>), [Stack](<by_topic/Stack.md>), [Monotonic Stack](<by_topic/Monotonic Stack.md>)** |
| 16 | +> |
| 17 | +> **Acceptance Rate** : **64.3 %** |
| 18 | +
|
| 19 | +------ |
| 20 | + |
| 21 | +## Solutions |
| 22 | + |
| 23 | +- [h42 v1 heap.py](<../my-submissions/h42 v1 heap.py>) |
| 24 | +- [h42 v2 two pointer.py](<../my-submissions/h42 v2 two pointer.py>) |
| 25 | +### Python |
| 26 | +#### [h42 v1 heap.py](<../my-submissions/h42 v1 heap.py>) |
| 27 | +```Python |
| 28 | +class Solution: |
| 29 | + def trap(self, height: List[int]) -> int: |
| 30 | + output = 0 |
| 31 | + |
| 32 | + vals = [(-x, i) for i, x in enumerate(height)] |
| 33 | + heapify(vals) |
| 34 | + |
| 35 | + left_max = right_max = heappop(vals)[1] |
| 36 | + while vals and (left_max > 0 or right_max < len(height) - 1): |
| 37 | + val, i = heappop(vals) |
| 38 | + val = -val |
| 39 | + |
| 40 | + if left_max <= i <= right_max : |
| 41 | + continue |
| 42 | + |
| 43 | + if i <= left_max : |
| 44 | + minn = min(val, height[left_max]) |
| 45 | + output += sum(minn - x for x in height[i + 1:left_max]) |
| 46 | + left_max = i |
| 47 | + else : |
| 48 | + minn = min(val, height[right_max]) |
| 49 | + output += sum(minn - x for x in height[right_max + 1:i]) |
| 50 | + right_max = i |
| 51 | + |
| 52 | + return output |
| 53 | +``` |
| 54 | + |
| 55 | +#### [h42 v2 two pointer.py](<../my-submissions/h42 v2 two pointer.py>) |
| 56 | +```Python |
| 57 | +class Solution: |
| 58 | + def trap(self, height: List[int]) -> int: |
| 59 | + left_max = right_max = output = 0 |
| 60 | + left, right = 0, len(height) - 1 |
| 61 | + |
| 62 | + while left < right : |
| 63 | + if height[left] < height[right] : |
| 64 | + output += (left_max := max(left_max, height[left])) - height[left] |
| 65 | + left += 1 |
| 66 | + else : |
| 67 | + output += (right_max := max(right_max, height[right])) - height[right] |
| 68 | + right -= 1 |
| 69 | + |
| 70 | + return output |
| 71 | +``` |
| 72 | + |
0 commit comments