trapping-rain-water py3

This commit is contained in:
Sangeeth Sudheer 2022-04-23 21:28:55 +05:30
parent a0b3f7f134
commit a115f39b17
4 changed files with 63 additions and 0 deletions

View File

@ -0,0 +1,8 @@
## Approaches:
1. Brute force $O(N^2)$
2. Two-pointer $O(N)$
## Follow-up questions
1. What if you could slant the container?

View File

@ -0,0 +1,22 @@
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:**
![](https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png)
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`

View File

@ -0,0 +1,33 @@
# Time: O(N · H) where H is the maximum height
# Space: O(1)
class Solution:
def trap(self, height: List[int]) -> int:
maxh = 0
for h in height:
maxh = max(h, maxh)
land_width = len(height)
output = 0
for i in range(maxh):
row_output = 0
trough_output = 0
trough_start = -1
for j in range(land_width):
# A block is present
if height[j] >= i + 1:
row_output += trough_output
trough_start = j
trough_output = 0
elif trough_start >= 0:
trough_output += 1
output += row_output
return output