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
思路:用一个数组leftmax[i]来存储i前最大的bar值,然后再从右边开始遍历列表并始终维护一个代表右边最大的bar值的数。
对于每个遍历的元素,该位置能储存的雨水量应为:min(左边最大的bar值,右边最大的bar值) - 当前位置的bar值。
这个算法的时间复杂度为O(n),源代码如下: