leetcode/0042_trapping-rain-water/python3/imaginary_grid.py

33 lines
845 B
Python

# 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