Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
For example,
Given [0,1,0,2,1,0,1,3,2,1,2,1]
, return 6
.
The above elevation map 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. Thanks Marcos for contributing this image!
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if not height:
return 0
height_len = len(height)
maxLeft = [0 for _ in range(height_len)]
maxRight = [0 for _ in range(height_len)]
max_value = height[0]
for index in range(height_len):
maxLeft[index] = max_value
if max_value < height[index]:
max_value = height[index]
max_value = height[height_len - 1]
for index in reversed(range(height_len)):
maxRight[index] = max_value
if max_value < height[index]:
max_value = height[index]
result = 0
for index in range(height_len):
water = min(maxRight[index], maxLeft[index]) - height[index]
if water > 0:
result += water
return result