[LC] 42. Trapping Rain Water

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.


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!

Example:

Input: [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

 1 class Solution(object):
 2     def trap(self, height):
 3         """
 4         :type height: List[int]
 5         :rtype: int
 6         """
 7         left, right = 0, len(height) - 1
 8         leftMax, rightMax, res = 0, 0, 0
 9         while left < right:
10             if height[left] <= height[right]:
11                 leftMax = max(leftMax, height[left])
12                 res += leftMax - height[left]
13                 left += 1
14             else:
15                 rightMax = max(rightMax, height[right])
16                 res += rightMax - height[right]
17                 right -= 1
18         return res

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/11829061.html