problem
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:
1 | Input: [0,1,0,2,1,0,1,3,2,1,2,1] |
1 | var trap = function(height) { |
method
这道题的思路是对每个位置,计算当前位置的min(rightMax, rightMax),然后减去当前位置的高度 ,在逐个相加
i的位置从左到右,j的位置从右到左
leftMax是nodecrease的,rightMax是noincrease的,所以,
leftMax >= rightMax, 那么rightMax所处的位置j就能确定当前min(rightMax, rightMax) 为rightMax,
leftMax < rightMax, 那么leftMax所处的位置i就能确定当前min(rightMax, rightMax) 为leftMax,