Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c86f3c9

Browse files
Trapping Rain Water
1 parent af25f1d commit c86f3c9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎42-trapping-rain-water.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/trapping-rain-water/
3+
4+
Given n non-negative integers representing an elevation map where the width of each bar is 1,
5+
compute how much water it can trap after raining.
6+
7+
Example 1:
8+
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
9+
Output: 6
10+
Explanation: The above elevation map (black section) is represented by array
11+
[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.
12+
13+
Example 2:
14+
Input: height = [4,2,0,3,2,5]
15+
Output: 9
16+
17+
Constraints:
18+
n == height.length
19+
1 <= n <= 2 * 104
20+
0 <= height[i] <= 105
21+
"""
22+
class Solution:
23+
def trap(self, height: List[int]) -> int:
24+
max_left = [height[0]]
25+
26+
for index in range(1, len(height)):
27+
max_left.append(max(max_left[-1], height[index]))
28+
29+
max_right = [0] * len(height)
30+
max_right[-1] = height[-1]
31+
32+
for index in range(len(height) - 2, -1, -1):
33+
max_right[index] = max(max_right[index+1], height[index])
34+
35+
total_water = 0
36+
for index in range(len(height)):
37+
total_water += min(max_left[index], max_right[index]) - height[index]
38+
39+
return total_water

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /