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!
public class Solution {
public int trap(int[] height) {
int sum = 0;
int pre;
int maxIndex = -1;
int max = -1;
for(int i = 0; i < height.length; i++){
if(height[i] > max){
max = height[i];
maxIndex = i;
}
}
pre = 0;
for(int i = 0; i < maxIndex; i++){
if(height[i] > pre){
sum += (height[i] - pre)*(maxIndex - i);
pre = height[i];
}
sum -= height[i];
}
pre = 0;
for(int i = height.length-1; i> maxIndex; i--){
if(height[i] > pre){
sum += (height[i] - pre)*(i - maxIndex);
pre = height[i];
}
sum -= height[i];
}
return sum;
}
}
sum = sum + (maxIndex - i )*(height[i] - pre) , 记录的是位置i时,所能存储的水量,之后在减去A[i]占据的空间,即是所能存存储的水量,比方maxIndex = 7, i = 1是,能存的水量是5,因为这时3到7之间都是空的,i = 3时,height[3] - pre = 1, 这指的是,板子变高了,高的那一部分多存的水量,应该是(2 - 1) * (7 - 3) = 4 , 再加上原来的sum = 5 就是现在的sum,之后减去height[3],即减去height[3]所占空间,得到的就是能存的水量,之后i= 4,5,6都没有i =2 高,所以能多存的水不再增加,减掉它们所占据的空间,就是左半边最终能存储的水量;右半边和左半边一样。